Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord find_or_build_by
    primarykey
    data
    text
    <p>I would like to perform:</p> <pre><code> XXX.find_or_build_by_language_id(attributes) </code></pre> <p>I found</p> <pre><code> XXX.find_or_initialize_by_language_id(attributes) </code></pre> <p>but that only set language_id and no other attributes. Even if I manually sets the attributes, the record is not saved when I perform XXX.save.</p> <p>I just read <a href="https://stackoverflow.com/questions/4844458">Rails - find or create - is there a find or build?</a>, which seems related to my problem but does not fit my needs.</p> <h2>Edit</h2> <p>Let's use this scenario</p> <pre><code># db/migrations/create_models.rb class CreateModels &lt; ActiveRecord::Migration def self.up create_table :companies do |t| t.string :name end create_table :employees do |t| t.string :name t.string :city t.references :company end end end </code></pre> <p>-</p> <pre><code># app/models/employee.rb class Employee &lt; ActiveRecord::Base belongs_to :company end </code></pre> <p>-</p> <pre><code># app/models/company.rb class Company &lt; ActiveRecord::Base has_many :employees end </code></pre> <p>-</p> <pre><code># rails console :001&gt; c = Company.new =&gt; #&lt;Company id: nil, name: nil&gt; :002&gt; c.employees =&gt; [] :003&gt; e = c.employees.find_or_initialize_by_name(:name =&gt; 'foo', :city =&gt; 'bar') =&gt; #&lt;Employee id: nil, name: "foo", city: "bar", company_id: nil&gt; :004&gt; c.employees =&gt; [] :005&gt; c.save =&gt; true :006&gt; c.employees =&gt; [] :007&gt; e.save =&gt; true :008&gt; c = Company.first =&gt; #&lt;Company id: 1, name: nil&gt; :009&gt; c.employees =&gt; [#&lt;Employee id: 1, name: "foo", city: "bar", company_id: 1&gt;] :010&gt; e = c.employees.find_or_initialize_by_name(:name =&gt; 'foo', :city =&gt; 'baz') =&gt; #&lt;Employee id: 1, name: "foo", city: "bar", company_id: 1&gt; :011&gt; e.city = 'baz' =&gt; "baz" :012&gt; c.employees =&gt; [#&lt;Employee id: 1, name: "foo", city: "bar", company_id: 1&gt;] :013 &gt; c.save =&gt; true :014&gt; c.employees =&gt; [#&lt;Employee id: 1, name: "foo", city: "bar", company_id: 1&gt;] </code></pre> <h2>Problems</h2> <ol> <li>:004 => The Employee from :003 is not added to c.employees</li> <li>:006 => The Employee from :003 is saved with c</li> <li>:010 => The city attribute of employee is not set</li> <li>:014 => THe city attribute of employee is not updated when saving company</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.
 

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