Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>this is easier than you might think because it's handled automatically by ActiveRecord.</p> <p>When you say "has_and_belongs_to_many", you're telling AR to associate those two models with a many-to-many relationship using the table, and for the most part you no longer need to worry about the join table. When you add an instance of Standard to an Rfq's list of standards, this will be done for you.</p> <p>Here's an example:</p> <pre><code>rfq = Rfq.create standard = Standard.create rfq.standards &lt;&lt; standard </code></pre> <p>We've created each of the objects, and the third line creates the connection, saving a new record in the rfqs_standards table with the proper ids. rqf.standards looks and acts like a normal array, but when you assign objects to it, ActiveRecord does the database work for you.</p> <p>After creating the records, you could have also done:</p> <pre><code>standard.rfqs &lt;&lt; rfq </code></pre> <p>You could also do both at the same time:</p> <pre><code>rfq = Rfq.create standard rfq.standards.create </code></pre> <p>This created an rfq, then created a standard that is <em>automatically</em> connected to the rfq. You can do the same thing in reverse:</p> <pre><code>standard = Standard.create rfq = standard.rfqs.create </code></pre> <p>I hope this helps!</p> <p><strong>UPDATE:</strong> Since you mentioned forms and automatic saving, read my article on <a href="http://kconrails.com/2010/10/19/common-addresses-using-polymorphism-and-nested-attributes-in-rails/" rel="nofollow" title="nested attributes">nested attributes</a> that shows how to implement that, including full code samples.</p>
 

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