× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Nested attributes and strong parameters

Gabe Odess
Dec 24, 2014
<p>In this session we covered using nested attributes to create an associated Profile record when submitting your new User form.</p><p>The first issue was that the fields_for tag was not using the form helper and so the fields were being sent without being nested.  We had to change:</p><pre><code class="language-ruby">&lt;%= fields_for :profile do |form| %&gt;</code></pre><p>to</p><pre><code class="language-ruby">&lt;%= f.fields_for :profile do |form| %&gt;</code></pre><p>After this we noticed that all the fields inside the block now disappeared.  This was because the Profile association on the User was blank.  In order to set it we had to update the form declaration from:</p><pre><code>&lt;%= form_for resource do |f| %&gt;</code></pre><p>to</p><pre><code>&lt;%= form_for resource.tap{|user| user.build_profile} do |f| %&gt;</code></pre><p>This brought all our Profile fields back.  The last step was too add the profile attributes to our list permitted attributes in the controller:</p><pre><code class="language-ruby">params.permit(:email, :password, :password_confirmation, :profile_attributes =&gt; [:first_name, :last_name, :zip])</code></pre><p>And that's it!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus