嵌套属性:3个图像中只有1个显示

时间:2014-05-16 19:01:25

标签: ruby-on-rails ruby-on-rails-4

我有帖子,评论和评论_images。每条评论都可以上传3张图片。显示所有3张图像时出现问题 - 它只显示最后选择的图像(1张图像)。我使用了多态关联,因为这些图像将来属于其他东西。

形式

<%= nested_form_for([@post, @comment], html: {multipart: true}, class: 'comments') do  |f| %>

  <%= f.text_area :content %>
...
    <%= f.fields_for :comment_images do |p| %>
        <%= p.file_field :image %>
        <%= p.file_field :image %>
        <%= p.file_field :image %>
    <% end %>
...
<% end %>

显示

<% @comment.comment_images.each do |pic| %>
     <%= link_to image_tag(pic.image_url(:comment_thumb)), pic.image_url, target: :_blank if pic.image?  %>
<% end %>

comment_images

class CommentImage < ActiveRecord::Base  
  belongs_to :attachable, polymorphic: true
  mount_uploader :image, ImageUploader 
end

评论

class Comment < ActiveRecord::Base
...
  has_many :comment_images, :as => :attachable, :dependent => :destroy
  accepts_nested_attributes_for :comment_images, :limit => 3
...
end

comments_controller

def comment_params
  params.require(:comment).permit(:content, :user_id, :post_id,
    comment_images_attributes: [:image, :attachable_id, :attachable_type])
end

1 个答案:

答案 0 :(得分:0)

您不必重复file字段。使用accepted_nested_attributes_for时,fields_for将为您执行迭代。所以将表单更改为:

<%= f.fields_for :comment_images do |p| %>
    <%= p.file_field :image %>
<% end %>

这不是必要的:

    <%= p.file_field :image %>
    <%= p.file_field :image %>
    <%= p.file_field :image %>

不要忘记在控制器中初始化三个子对象。

@comment = Comment.new(images: images) #=> where images is an array of three image objects
相关问题