Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested attributes for has_one association

I'm in need to setup attributes for has one association in new and edit actions, so I have this:

Product model

has_one :store
accepts_nested_attributes_for :store

form

= form_tag @product do |f|
  = f.fields_for :store do |store_fields|
    = render 'store_form', :f => store_fields

in controller

params.require(:store).permit(:store).permit!

fields displays, but when I'm submitting form, it doesn't make sense, store association is empty. How problem can be solved?

UPD

params.require(:product).permit(store_attributes: [:store_id, :supplier_id, :margin, :discount]).permit!

Logs:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "product"=>{"name"=>"qwefqwefasdf", "description"=>"", "permalink"=>"asdf", "store_attributes"=>{"margin"=>"123", "discount"=>"123"}}, "button"=>"", "id"=>"asdf"}
like image 790
Mark Pegasov Avatar asked Dec 19 '13 18:12

Mark Pegasov


2 Answers

Ok, the right answer is

change

  = f.fields_for :store do |store_fields|

to

  = f.fields_for :store, @vendor.store do |store_fields|
like image 84
Mark Pegasov Avatar answered Oct 20 '22 13:10

Mark Pegasov


Make sure the params you expect are being sent. (check pluralization)

Can you copy and paste what the params look like from the server side?

13:44:29 INFO:   Parameters: {"utf8"=>"✓" .......

That will help to get the naming the params correctly

If params naming is correct, but not being accepted for, then try specifying them explicitly

params.permit(:product => [:something, :stores_attributes => [:name, :address ]])

Update:

params.permit(:product => [ :name, :description, :permalink, :store_attributes => [:store_id, :supplier_id, :margin, :discount]])

Nested Attributes Examples:

http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

like image 38
Andrew Wei Avatar answered Oct 20 '22 13:10

Andrew Wei