我有一个product.rb
class Product < ApplicationRecord
belongs_to :category
has_many :comments,dependent: :destroy
has_many :photos,inverse_of: :product
accepts_nested_attributes_for :photos ,reject_if: :all_blank, allow_destroy: true
end
product_controller.rb
def new
@product=Product.new
@product.photos.new
end
def product_params
params.require(:product).permit(:name,:price,:decription,:category_id,photos_attributes: [:avatar])
end
product / new.html.erb
<%= simple_form_for @product do |f| %>
<%= f.input :name %>
<%= f.input :price %>
<%= f.input :decription, as: :text%>
<%= f.select :category_id , @categorys.collect{|c|[c.name,c.id]},include_blank:false %></br>
<h2> photo</h2>
<%= f.simple_fields_for :photos do |photo|%>
<%= render 'photo_fields', f:photo %>
<%=link_to_add_association 'add photo', f, :photos%>
<%end%>
<%=f.submit%>
<% end %>
<%= link_to 'Back', products_path %>
_photo_fields.html.erb
<%= f.input :avatar , as: :file%>
<%= link_to_remove_association "remove photo", f %>
,我上传了多张用于产品的照片。但是当我显示产品的所有照片时,产品仅保存了一张照片 图片
<strong>image</strong>
<% @product.photos.each do |p| %>
<%= image_tag p.avatar.url(:medium) %>
<% end %>%>
我希望产品有很多照片(关联1 -n)。对不起,我英语不好。请帮助我!