ruby on rails - Prefill a nested element with simple_form -


is possible pre-fill simple_fields_for input datas object ?

i have user object. user has_one backpack, backpack has many pockets, , pocket has_many items

when building form, i'm using

    <%= f.simple_fields_for :backpack |backpack| %>       <%= render 'backpack', f:backpack %>     <% end %> 

now, when i'm on users#new, whole form empty. initialize backpack fields datas backpack object, possible ? tried doing this:

    <%= f.simple_fields_for :backpack, @backpack |backpack| %>       <%= render 'backpack', f:backpack %>     <% end %> 

along in userscontroller:

@user = user.new @backpack = backpack.find(1).deep_clone include: [ :pockets, { pockets: :items } ] 

but doesn't work: reason, backpack fields filled, pockets , items empty. tried pretty came mind: checked routes nested objects, tried , without deep_cloning, still, nested objects found, makes me wonder, possible initialize form prefilled nested models?

edit:

ok, reason, when put a

<% @backpack.pockets.each |pocket| %>     <%= pocket.title %> <% end %> 

it displays of pockets titles, means cloned backpack, but, using this:

<%= f.simple_fields_for :pockets, @backpack.pockets |pocket| %>   <%= render 'pocket', f: pocket %> <% end %> 

nothing displayed.

ok, so, appears clone not saved, therefore, using prefill simple_fields_for results in prefilling direct attributes, , none of nested models, therefore, you'll have save clone, remove attributes requestion params, , create separately

@backpack = backpack.find(1).deep_clone include: [ :pockets, { pockets: :items } ] @backpack.save 

and then, in users#create method

@user = user.new(user_params.except(:backpack_attributes)) @backpack = backpack.new(params[:user][:backpack]) @backpack.save @user.backpack = @backpack 

this way, you'll have new user, , form prefilled backpack attributes , nested attributes.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -