0

It's been a week and I'm still stuck trying to create a new form that updates my associated model. I have read so many post with a similar problem and is killing me inside.

The same old Gallery has_many :photosand Photo belongs_to :gallery I have already nested my resources. When I submit my form I also get a routing error.

    resources :galleries do
        resources :photos do
        end
    end

Already included accepted_nested_attribute_for :photos in my :gallery model How should I write my new and create method for my photos controller? Should I use .build instead of .create, should I use fields_for instead of form_for? I notice rails 4 is using strong params, so do I need to permit gallery inside my photos controller.

Sorry guys I read, and watched so many videos and even though I copy code for code still stuck.

My simple_form keeps on getting all sorts of error:

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

My goal is to pass on my gallery's id to my photos. This is my scheme:

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
4

1 回答 1

0

因此,您有一个用于在图库中插入多张图片的图库表单,您需要从参数中获取图库。

首先在你的photos_controller.rb

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

和你的表格,你应该使用 cocoon 或nested_form_fields(我的首选)

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

通过做白名单参数

def params
  params.require(:gallery).permit(:gallery, :stuff, :in_here, pictures: [:pictures, :stuff, :in_here])
end
于 2016-03-03T19:05:46.743 回答