Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To model the relationships you described you would do:</p> <pre><code>models/category.rb class Category &lt; ActiveRecord::Base has_many :products has_many :subcategories, :class_name =&gt; "Category", :foreign_key =&gt; :parent_id end models/product.rb class Product &lt; ActiveRecord::Base belongs_to :product has_many :features, :through =&gt; :product_features has_many :product_features end models/feature.rb class Feature &lt; ActiveRecord::Base has_many :product_features has_many :products, :through =&gt; :product_features end models/productfeature.rb class ProductFeature &lt; ActiveRecord::Base belongs_to :product belongs_to :feature end </code></pre> <p>Given this structure then you have the join modelled as a Many-to-Many relation. This is useful since the HABTM style of join is going away in Rails 3.1</p> <p>To get the information, I often use the console <strong>rails console</strong> for testing and this would allow you do do</p> <pre><code>@category = Category.first #get the first category @category.subcategories #returns an array of categories </code></pre> <p>The traversal of the links is via the relations that you setup in the models, with the intention that its <strong>readable</strong>, in the context of using sensible names. The self-joins, as per your question, is also covered in <a href="http://guides.rubyonrails.org/association_basics.html#self-joins" rel="nofollow">Rails Guides: Associations</a> with a good example. The rest of this guide also details the other relationships.</p> <p>One other thing to remember is to create your migrations so that the join table is created with the id's which are the foreign keys.</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