RoR:表单中的嵌套字段

RoR: Nested field in form

我有一个应用程序,用户可以在其中创建 gallery,he/she 可以附加一些图片。为此,我使用载波,其结构如下。 每个gallery有很多pictures,每个picture有1个image

class Gallery < ActiveRecord::Base
    has_many :pictures, dependent: :destroy
    accepts_nested_attributes_for :pictures, allow_destroy: true;
end
class Picture < ActiveRecord::Base
    belongs_to :gallery
    mount_uploader :image, ImageUploader
end

图片上传格式如下

<%= form_for(@gallery, html: {multipart: true}) do |f| %>
    <%= f.label :title %><br />
    <%= f.label :pictures %><br />
    <% if @gallery.pictures %>
        <ul class="form-thumbs clearfix">
        <% @gallery.pictures.each do |picture| %>
            <li>
                <%= image_tag(picture.image) %> 
                <%= link_to "Delete", gallery_picture_path(@gallery, picture), method: :delete %>
           </li>
        <% end %>
        </ul>
    <% end %>
    <%= file_field_tag "images[]", type: :file, multiple: true %>
<% end %>

然后用下面的动作处理

class GalleriesController < ApplicationController
    def create
        @gallery = Gallery.new(gallery_params)
        if @gallery.save
            if params[:images]
                params[:images].each do |image|
                    @gallery.pictures.create(image: image)
                end
            end
        end
    end
 end

这一切都很好,但现在我想添加一个嵌套字段:title,这样当我打开表单并且有图片上传时,我可以给每张图片一个标题。任何人都可以向我解释如何以现有形式适应它吗?

你最好做到以下几点:

#app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
   def new
       @gallery = Gallery.new
       @gallery.pictures.build
   end

   def create
       @gallery = Gallery.new gallery_params
       @gallery.save
   end

   private

   def gallery_params
       params.require(:gallery).permit(:title, pictures_attributes: [:image, :title])
   end
end

这将使您能够使用以下内容:

#app/views/galleries/new.html.erb
<%= form_for @gallery do |f| %> 
   <%= f.text_field :title %>
   <%= f.fields_for :pictures do |p| %>
      <%= p.text_field :title %>
      <%= p.file_field :image %>
   <% end %>
   <%= f.submit %>
<% end %>

这会将您需要的属性传递给关联的模型。