Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>do_something_with( item.collection_item_id ) </code></pre> <p>This fails because item does not have a collection_item_id member.</p> <pre><code>do_something_with( item.collection_item.collection_item_id ) </code></pre> <p>This fails because item does not have a collection_item member.</p> <p>Remember that the relation between item and collection_items is a has_many. So item has collection_items, not just a single item. Also, each collection has a list of collection items. What you want to do is probably this:</p> <pre><code>colls = Collection.find :all colls.each do |coll| coll.collection_items.each do |collection_item| do_something_with( collection_item.id ) end end </code></pre> <p>A couple of other pieces of advice:</p> <ul> <li>Have you read the <a href="http://guides.rubyonrails.org/association_basics.html#thehas-manythroughassociation" rel="nofollow noreferrer">documentation for has_many :through</a> in the Rails Guides? It is pretty good.</li> <li>You shouldn't need the :source parameters in the has_many declarations, since you have named your models and associations in a sensible way.</li> </ul> <blockquote> <p>I found from online documentation that using has_and_belongs_to_many will attach the join table attributes to the retreived items, but apparently it is deprecated. I haven't tried it yet.</p> </blockquote> <p>I recommend you stick with has_many :through, because has_and_belongs_to_many is more confusing and doesn't offer any real benefits.</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