Note that there are some explanatory texts on larger screens.

plurals
  1. POrails fields_for and nested attributes
    primarykey
    data
    text
    <p>I have difficulty to understand how to use fields_for and nested attributes. In order to understand it better, I created a <a href="https://github.com/nyror/nested_attributes" rel="nofollow noreferrer">repo</a>, which is not working. </p> <p>I read <a href="https://stackoverflow.com/questions/4480187/fields-for-for-nested-attribute-returns-nothing">this</a>, which is not helpful. </p> <p>I am using:</p> <p>Rails 4.0.1 Ruby 2.0.0-p247</p> <h3>Question:</h3> <ol> <li>address form shown, why can not save to database?</li> <li><p>Why not work?</p> <p><code>jack = Person.create(name: 'Jack')</code></p> <p><code>jack.address.create(street: '12w 33st')</code></p></li> </ol> <p>The main function is as below:</p> <pre><code>#model class Person &lt; ActiveRecord::Base has_one :address accepts_nested_attributes_for :address end class Address &lt; ActiveRecord::Base belongs_to :person end </code></pre> <p>view as below:</p> <pre><code>&lt;%= form_for(@person) do |f| %&gt; &lt;% if @person.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt;&lt;%= pluralize(@person.errors.count, "error") %&gt; prohibited this person from being saved:&lt;/h2&gt; &lt;ul&gt; &lt;% @person.errors.full_messages.each do |msg| %&gt; &lt;li&gt;&lt;%= msg %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="field"&gt; &lt;%= f.label :name %&gt;&lt;br&gt; &lt;%= f.text_field :name %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= f.label :age %&gt;&lt;br&gt; &lt;%= f.text_field :age %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= f.label :gender %&gt;&lt;br&gt; &lt;%= f.text_field :gender %&gt; &lt;/div&gt; &lt;%= fields_for :address do |address_fields|%&gt; Street: &lt;%= address_fields.text_field :street%&gt; Zip code: &lt;%= address_fields.text_field :zip_code%&gt; &lt;% end %&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p><a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for" rel="nofollow noreferrer">nested attributes</a></p> <h3>Conclusion:</h3> <ol> <li>has_one relation does not support <code>person.address.create</code>. That's only for has_many</li> <li>rails api for <code>fields_for</code>, is really not clear. It's just missing the whole controller part. Follow it will not make it.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload