2015-10-19 106 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