5

阶段

图像画廊应用程序。我有两个模型HandcraftPhotos. 一个手工艺品可能有很多照片,假设我有这样的模型:

  • Handcraft(name:string)
  • Photo(filename:string, description:string, ...)

_form.html.erb手工艺品中,有:

<%= form_for @handcraft, html: {multipart: true} do |f| %>
  # ... other model fields

  <div class="field">
    <%= f.label :photo %><br />
    <%= f.file_field :photo %>
  </div>

  # ... submit button
<% end %>

handcraft.rb看起来像这样:

class Handcraft < ActiveRecord::Base
  attr_accessible :photo
  has_many :photos
  mount_uploader :photo, PhotoUploader
  # ... 
end

photo_uploader.rb

class PhotoUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :thumb do
    process :resize_to_limit => [100, 100]
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

问题

当我提交表单时,它会引发此错误:

NoMethodError (undefined method `photo_will_change!' for #<Handcraft:0xb66de424>):

问题

在这种情况下,我应该如何使用/配置 Carrierwave?

4

1 回答 1

11

您需要将上传器安装在将存储文件名的字段上,因此您的模型应该看起来像

class Handcraft < ActiveRecord::Base
  attr_accessible :name
  has_many :photos
  # ... 
end

class Photo < ActiveRecord::Base
  attr_accessible :filename, :description
  mount_uploader :filename, PhotoUploader
  # ... 
end

然后看起来您将通过手工表格创建照片,您应该添加

accepts_nested_attributes_for :photos

在你的Handcraft课上

然后你的表格看起来像

<%= form_for @handcraft, html: {multipart: true} do |f| %>
  # ... other model fields

  <%= f.fields_for :photos do |photo| %>
    <%= photo.label :photo %><br />
    <%= photo.file_field :photo %>
  <% end %>

  # ... submit button
<% end %>

对于显示照片字段的表单,您需要创建Handcraft实例photos,这可以在您的new方法中完成,HandcraftsController如下所示:

def new
  @handcraft = Handcraft.new
  4.times { @handcraft.photos.build }
end

这将使表单中的 4 个(任意数字)字段可用,如果您希望用户以某种方式在表单中动态添加新照片,请查看nested_form

于 2012-11-01T14:09:31.237 回答