Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdate Mapping Table Attribute in Many to Many Association
    text
    copied!<p>I have a many to many association setup in Rails with ActiveRecord. Let's say the tables are </p> <pre><code>+------------+ +----------------+ +----------+ | categories | -- has many -= | category_items | =- has many -- | products | +------------+ +----------------+ +----------+ </code></pre> <p>In the category_items table I have the standard set of id's plus an extra attribute called "type": </p> <pre><code>id:int category_id:int product_id:int category_type:string </code></pre> <p>Thankfully, Rails provides some great helpers for making assignment in the mapping table a breeze. For example:</p> <pre><code>p = Product.first # p.id =&gt; 1 c = Category.first # c.id =&gt; 1 # now to make the assignment p.categories &lt;&lt; c # or p.categories.create(c) </code></pre> <p>That's all well and good, but let's say I want to automatically update the "type" field with the class name of the other table. So for the examples given above, my category_items row would look like this:</p> <pre><code>id = 1 (or some number) category_id = 1 product_id = 1 category_type = nil </code></pre> <p>But I would like category_type to equal "Product". Is there a way for me to build a callback or define something in the association that would automatically set the category_type field? I know in polymorphic associations, you can use something like :source or :as to do something like this, but polymorphic associations in many to many associations throws an error.</p> <p>Any ideas?</p> <p>Thanks!</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