Note that there are some explanatory texts on larger screens.

plurals
  1. PORails has_many :through and Setting Property on Join model
    primarykey
    data
    text
    <p>Similar to <a href="https://stackoverflow.com/questions/408872/rails-has-many-through-find-by-extra-attributes-in-join-model">this question</a>, how do I set a property on the join model just before save in this context?</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :post_assets has_many :assets, :through =&gt; :post_assets has_many :featured_images, :through =&gt; :post_assets, :class_name =&gt; "Asset", :source =&gt; :asset, :conditions =&gt; ['post_assets.context = ?', "featured"] end class PostAssets &lt; ActiveRecord::Base belongs_to :post belongs_to :asset # context is so we know the scope or role # the join plays validates_presences_of :context end class Asset &lt; ActiveRecord::Base has_many :post_assets has_many :posts, :through =&gt; :post_assets end </code></pre> <p>I just want to be able to do this:</p> <pre><code>@post = Post.create!(:title =&gt; "A Post") @post.featured_images &lt;&lt; Asset.create!(:title =&gt; "An Asset") # ... @post = Post.first @featured = @post.featured_images.first #=&gt; #&lt;Asset id: 1, title: "An Asset"&gt; @featured.current_post_asset #=&gt; #&lt;PostAsset id: 1, context: "featured"&gt; </code></pre> <p>How would that work? I've been banging my head over it all day :).</p> <p>What currently happens is when I do this:</p> <pre><code>@post.featured_images &lt;&lt; Asset.create!(:title =&gt; "An Asset") </code></pre> <p>Then the join model <code>PostAsset</code> that gets created never gets a chance to set <code>context</code>. How do I set that context property? It looks like this:</p> <pre><code>PostAsset.first #=&gt; #&lt;PostAsset id: 1, context: nil&gt; </code></pre> <p><strong>Update</strong>:</p> <p>I have created a test <a href="http://github.com/viatropos/acts-as-joinable" rel="nofollow noreferrer">gem</a> to try to isolate the problem. Is there an easier way to do this?!</p> <p>This <a href="http://github.com/viatropos/acts-as-joinable/blob/master/lib/acts_as_joinable/core.rb" rel="nofollow noreferrer">ActsAsJoinable::Core class</a> makes it so you can have many to many relationships with a context between them in the join model. And it adds helper methods. The basic <a href="http://github.com/viatropos/acts-as-joinable/blob/master/test/test_acts_as_joinable.rb" rel="nofollow noreferrer">tests</a> show basically what I'm trying to do. Any better ideas on how to do this properly?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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