簡體   English   中英

使用Carrierwave與模型之間的一對多關系

[英]Use Carrierwave with a one to many relation between models

階段

圖像庫應用程序。 我有兩個模型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?

您需要在將存儲文件名的字段上安裝上傳器,因此您的模型應如下所示

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 ,這可以在HandcraftsController中的new方法中完成,如下所示:

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

這將使您的表單中有4個(任意數字)字段可用,如果您希望用戶以某種方式在表單中動態添加新照片,請查看nested_form

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM