我们正在尝试通过Paperclip gem将多个图片上传到我们的产品型号。问题是,每次我们提交表单时,已经附加到产品的每个现有图像都会再次添加,但没有任何属性。我们创建了以下嵌套表单:
<div class="product-form">
<%= nested_form_for [:admin, @product], :html => { :multipart => true } do |f| %>
<div>
<%= f.label :category %><br>
<%= f.select :category_id, Category.all.map{ |s| [s.name, s.id]}, :include_blank => true %>
</div>
<div>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
</div>
<div>
<%= f.label :price %><br>
<%= f.number_field :price %><br>
</div>
<div>
<%= f.label :discount %><br>
<%= f.number_field :discount, :step => "any" %><br>
</div>
<div>
<%= f.label :description %><br>
<%= f.text_area :description %><br>
</div>
<table>
<%= f.fields_for :stocks %>
<tr>
<td><%= f.link_to_add "Add size", :stocks %></td>
</tr>
</table>
<br>
<table>
<%= f.fields_for :images %>
<tr>
<td><%= f.link_to_add "Add image", :images %></td>
</tr>
</table>
<%= f.submit %>
<% end %>
</div>
其中寻找以下部分:
<tr>
<% if f.object.new_record? %>
<td><%= f.file_field :image %></td>
<% else %>
<td><%= f.object.image_file_name %></td>
<%= f.hidden_field :_destroy %>
<td><%= f.link_to_remove "Remove" %></td>
<% end %>
</tr>
图片模型
class Image < ActiveRecord::Base
belongs_to :product
has_attached_file :image, :styles => { :medium => "300x300", :thumb => "100x100" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]
end
产品型号:
class Product < ActiveRecord::Base
# Associations
has_many :line_items
has_many :carts, :through => :line_items
has_many :stocks, :dependent => :destroy
has_many :images, :dependent => :destroy
belongs_to :category
accepts_nested_attributes_for :stocks, :images, :allow_destroy => true
# Validations
validates_presence_of :name, :price, :description, :category
def create_stock(size, amount)
Stock.create(size: size, amount: amount, product: self)
end
def self.categories
Product.pluck(:category).uniq
end
def sizes_in_stock
stocks.where.not(amount: 0).map{ |s| s.size }
end
def price_after_discount
has_discount? ? (self.price * self.discount/100).round(2) : price
end
def has_discount?
!self.discount.nil?
end
end
非常感谢任何帮助,谢谢