2016-03-03 113 views
0

這已經過去了一個星期,我仍然試圖創建一個新的表單來更新我的關聯模型。我已經閱讀了許多帖子,發現類似的問題,並在裏面殺了我。Simple_form Rails 4中的嵌套屬性

古同Galleryhas_many:photosPhotobelongs_to:gallery 我已經嵌套我的資源。當我提交表單時,我也收到路由錯誤。

resources :galleries do 
     resources :photos do 
     end 
    end 

已經包含在我的:gallery模型accepted_nested_attribute_for :photos 我應該怎麼寫我的新和我的照片控制器創建方法?我應該使用.build而不是.create,我應該使用fields_for而不是form_for?我注意到rails 4使用強烈的參數,所以我需要允許我的照片控制器中的畫廊。

對不起,我閱讀過,看過這麼多的視頻,儘管我複製代碼仍然卡住了。

我simple_form不斷收到各種錯誤的:

<%= simple_form_for :photos, html:{multipart: true} do |f| %> 
     <%= f.input :position, collection: 1..10 %> 
     <%= f.input :publish %> 
     <%= f.input :caption, placeholder:"Please insert caption here", label:false %> 
     <%= f.input :image, label:false %> 
     <%= hidden_field_tag 'user_id', current_user.id %> 
     <%= hidden_field_tag 'gallery_id', gallery.id %> 
     <%= f.button :submit %> 
    <% end %> 

我的目標是在我的圖片庫的ID傳遞給我的照片。這是我的計劃:

create_table "photos", force: :cascade do |t| 
    t.text  "caption" 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    t.integer "gallery_id" 
    t.datetime "created_at",   null: false 
    t.datetime "updated_at",   null: false 
    t.integer "position" 
    t.boolean "publish" 
end 
create_table "galleries", force: :cascade do |t| 
    t.string "title" 
    t.text  "description" 
    t.datetime "created_at",   null: false 
    t.datetime "updated_at",   null: false 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    t.integer "user_id" 
    t.string "tag" 
    t.boolean "publish" 
end 

回答

0

因此,您有一個畫廊窗體插入多個圖片在您的畫廊,您需要從參數中獲取畫廊。

首先,在您的photos_controller.rb

def new 
    @gallery = Gallery.find(params[:gallery_id) 
    @gallery.photos.build 
end 

和表單,你應該做

def params 
    params.require(:gallery).permit(:gallery, :stuff, :in_here, pictures: [:pictures, :stuff, :in_here]) 
end 
使用繭或 nested_form_fields(我的首選)

simple_form_for @gallery do |f| 
    f.simple_fields_for :pictures do |p| 
    p.input :title 
    p.input :your_other_stuff 

白名單的PARAMS