Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I was able to get this working for one of my models:</p> <pre><code>class Group &lt; ActiveRecord::Base has_many :users, :through =&gt; :memberships, :source =&gt; :user do def with_join proxy_target.map do |user| proxy_owner = proxy_owner() user.metaclass.send(:define_method, :membership) do memberships.detect {|_| _.group == proxy_owner} end user end end end end </code></pre> <p>In your case, something like this should work (haven't tested):</p> <pre><code>class Collection &lt; ActiveRecord::Base has_many :collection_items, :order =&gt; :position has_many :items, :through =&gt; :collection_items, :source =&gt; :item, :order =&gt; :position do def with_join proxy_target.map do |items| proxy_owner = proxy_owner() item.metaclass.send(:define_method, :join) do collection_items.detect {|_| _.collection == proxy_owner} end item end end end end </code></pre> <p>Now you should be able to access the CollectionItem from an Item as long as you access your items like this (<code>items.with_join</code>):</p> <pre><code>def helper_method( collection_id ) colls = Collection.find :all colls.each do |coll| coll.items.with_join.each do |item| do_something_with( item.join.collection_item_id ) end end end </code></pre> <p>Here is a more general solution that you can use to add this behavior to any <code>has_many :through</code> association: <a href="http://github.com/TylerRick/has_many_through_with_join_model" rel="nofollow">http://github.com/TylerRick/has_many_through_with_join_model</a></p> <pre><code>class Collection &lt; ActiveRecord::Base has_many :collection_items, :order =&gt; :position has_many :items, :through =&gt; :collection_items, :source =&gt; :item, :order =&gt; :position, :extend =&gt; WithJoinModel end </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