2015-10-19 107 views
1

我有一个应用程序,用户可以创建一个gallery,他/她可以附上一些图片。我使用carrierwave来达到这个目的,它的结构如下。 每个gallery有许多pictures和每个picture有1 imageRoR:嵌套字段形式

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,这样当我打开表格,并且有图片上传时,我可以给每张图片标题。任何人都可以解释我如何适应现有的形式?

回答

1

你会得到更好的执行以下操作:

#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 %> 

这会传给你需要的属性,以您的关联模型。

+0

谢谢你的回答丰富。即使'图片'表中存在'标题'列,我也会在#<图片::ActiveRecord_Associations_CollectionProxy:0x007f1ee01d7c10>中得到以下错误'未定义方法'标题' – sjbuysse

+0

如果删除'p.text_field:title '测试? –

+0

或多或少,我现在可以加载表格,但是当我提交时我没有创建图片(我也没有在你写的动作中看到它) – sjbuysse