Ruby on rails 在模型之间使用具有一对多关系的Carrierwave

Ruby on rails 在模型之间使用具有一对多关系的Carrierwave,ruby-on-rails,ruby-on-rails-3.2,carrierwave,has-many,Ruby On Rails,Ruby On Rails 3.2,Carrierwave,Has Many,舞台 图像库应用程序。 我有两个模型手工艺品和照片。 一个手工艺品可能有很多照片,假设我有这样的模型: class Handcraft < ActiveRecord::Base attr_accessible :photo has_many :photos mount_uploader :photo, PhotoUploader # ... end 手工艺品(名称:string) Photo(文件名:string,描述:string,…) 在手工艺品的\u form

舞台

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

class Handcraft < ActiveRecord::Base
  attr_accessible :photo
  has_many :photos
  mount_uploader :photo, PhotoUploader
  # ... 
end
  • 手工艺品(名称:string)
  • Photo(文件名:string,描述:string,…)
在手工艺品的
\u 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 %>
photo\u 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
类PhotoUploader[100100] 结束 def扩展白名单 %w(jpg jpeg gif png) 结束 结束 问题

当我提交表单时,它会抛出以下错误:

NoMethodError (undefined method `photo_will_change!' for #<Handcraft:0xb66de424>):
NoMethodError(未定义的方法'photo_will_change!',用于#):
问题


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

您需要在存储文件名的字段上装载上载程序,因此您的模型应该如下所示

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

class Photo < ActiveRecord::Base
  attr_accessible :filename, :description
  mount_uploader :filename, PhotoUploader
  # ... 
end
在你的
手工艺品中

然后你的表单看起来像

<%= 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 %>
这将使表单中有4个(任意数量)字段可用,如果您希望用户在表单中动态添加新照片,请查看

<%= 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 %>
def new
  @handcraft = Handcraft.new
  4.times { @handcraft.photos.build }
end