Note that there are some explanatory texts on larger screens.

plurals
  1. POget name of object following 2 time a relationship (2x has_many)
    primarykey
    data
    text
    <p>I have an author, who writes products, which are placed in groups. What I want to do is to list the groups that an author is involved into.</p> <p>So, I have first to follow the link from author to products, which works with :</p> <pre><code>@author = Author.find(params[:id]) @products = @author.products </code></pre> <p>which gives lot of products :-) Then I have to find (all) the groups that are linked to all of the products (because a group can contain a lot of products, I have already a has_many link with group_id column in the product table)</p> <p>But when I try to write something as</p> <pre><code>@groups = @author.products.groups </code></pre> <p>I get the error : undefined method `groups' for # Class:0x000000032a2198</p> <p>Why ?</p> <p>Here is the model, where only the "through" clauses seem not to work ?</p> <pre><code>class Author &lt; ActiveRecord::Base has_and_belongs_to_many :products has_many :groups, :through =&gt; :products end class Product &lt; ActiveRecord::Base belongs_to :group has_and_belongs_to_many :authors end class Group &lt; ActiveRecord::Base has_many :products, :dependent =&gt; :destroy has_many :authors, :through =&gt; :products end </code></pre> <p>Thanks !</p> <p>Edit : I found an ugly way to do what I want. <strong>But is there no better RoR way ??</strong></p> <pre><code>def show @author = Author.find(params[:id]) @products = @author.products @groups = [] @products.each do |product| group = Group.find(product.group_id) unless @groups.include?(group) @groups &lt;&lt; group end end end </code></pre>
    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.
    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