Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know this doesn't address the error you're getting, but I'd suggest using three one-to-many relationships instead of one many-to-many relationship.</p> <p>The conventional purpose of <code>has_many :through =&gt; ...</code> (many-to-many) is for when you have something like <code>students</code> and <code>classes</code>. A student can be in <strong>any</strong> number of classes. A class can have <strong>any</strong> number of students. Totally arbitrary numbers on both sides of the relationship.</p> <p>But that isn't your situation here. Your projects can be in exactly one main category, one optional category 1, and one optional category 2. It's a totally different problem and it isn't the problem that <code>has_many :through</code> is designed to solve.</p> <p>I suggest this arrangement:</p> <pre><code>class Project &lt; ActiveRecord::Base belongs_to :main_category, :class_name =&gt; "Category", :foreign_key =&gt; 'main_category_id' belongs_to :optional_category_1, :class_name =&gt; "Category", :foreign_key =&gt; 'optional_category_1_id' belongs_to :optional_category_2, :class_name =&gt; "Category", :foreign_key =&gt; 'optional_category_2_id' end class Category &lt; ActiveRecord::Base has_many :main_category_projects, :class_name =&gt; "Project", :foreign_key =&gt; 'main_category_id' has_many :optional_category_1_projects, :class_name =&gt; "Project", :foreign_key =&gt; 'optional_category_1_id' has_many :optional_category_2_projects, :class_name =&gt; "Project", :foreign_key =&gt; 'optional_category_2_id' end </code></pre> <p>Then you'll be able to do stuff like:</p> <pre><code>my_project.main_category my_category.optional_category_1_projects # etc... </code></pre>
 

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