简体   繁体   中英

How to deal with nested form and strong parameters in rails 4

I have a rails 4 application where I try to fill Post and Detail models. The relation between the models is has_one. I PostController I have :

def post_params
  params.require(:post).permit(:title, :email, :tel, :detail_attributes => [:id, :description, :post_id])
end

and my form is :

<%= f.fields_for @post.detail do |builder| %>
  <%= render "detail_form", detail: builder%>
<% end %>

` When I inspect post_params I get : {"title"=>"", "email"=>"toto@example.com", "tel"=>""}

How can I whitelist detail attributes?

Thank you

Please try this

class Post < ActiveRecord::Base
  has_one :detail
  accepts_nested_attributes_for :detail, allow_destroy: true
end

<%= form_for @ost do |f| %>
  <%= f.fields_for :detail do |builder| %>
    <%= render "detail_form", detail: builder%>
  <% end %>
<% end %>

Your line for StrongParameters' require / permit code looks right. Like Prashant4224 answered, did you include the accepts_nested_attributes_for in your model.rb?

class Post < ActiveRecord::Base
  has_one :detail
  accepts_nested_attributes_for :detail
end

Sidenote: if you choose to add allow_destroy: true , you will need to add _destroy to your permit line in your controller like so:

def post_params
  params.require(:post).permit(:title, :email, :tel, :detail_attributes => [:id, :description, :post_id, :_destroy])
end

If you already have accepted nested parameters in your model, your form may be failing to send those parameters. You should inspect the parameters before post_params is called, and debug your view code from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM