Simple_form Rails 4中的嵌套属性
问题描述:
这已经过去了一个星期,我仍然试图创建一个新的表单来更新我的关联模型。我已经阅读了许多帖子,发现类似的问题,并在里面杀了我。Simple_form Rails 4中的嵌套属性
古同Gallery
has_many
:photos
和Photo
belongs_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
答
因此,您有一个画廊窗体插入多个图片在您的画廊,您需要从参数中获取画廊。
首先,在您的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