Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't define :joins conditions in has_many relationship?
    primarykey
    data
    text
    <p>I have a relationship table :</p> <pre><code>create_table "animal_friends", :force =&gt; true do |t| t.integer "animal_id" t.integer "animal_friend_id" t.datetime "created_at" t.datetime "updated_at" t.integer "status_id", :default =&gt; 1 end </code></pre> <p>linking animals to others. Best way to retreive associations in SQL is :</p> <pre><code>SELECT animals.* from animals join animal_friends as af on animals.id = case when af.animal_id = #{id} then af.animal_friend_id else af.animal_id end WHERE #{id} in (af.animal_id, af.animal_friend_id) </code></pre> <p>And I can't find a way to create a proper has_many relation in rails with this. Apparently, there's no way to provide joining conditions for has_many.</p> <p>I'm currently using a finder_sql :</p> <pre><code>has_many :friends, :class_name =&gt; "Animal", :finder_sql =&gt; 'SELECT animals.* from animals join animal_friends as af on animals.id = case when af.animal_id = #{id} then af.animal_friend_id else af.animal_id end ' + 'WHERE #{id} in (af.animal_id, af.animal_friend_id) and status_id = #{Status::CONFIRMED.id}' </code></pre> <p>but this method has the great disadvantage of breaking activerecord magic. For instance :</p> <pre><code>@animal.friends.first </code></pre> <p>will execute the finder_sql without limit, fetching thousands of rows, then taking the first of the array (and loosing several precious <em>seconds</em> / req).</p> <p>I guess it's a missing feature from AR, but I'd like to be sure first :) Thanks</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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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