This project is archived and is in readonly mode.
has_many association_condition option
-
Gravis
I would +1 for a :joins options, allowing to specify the joining conditions on a has_many assoc (or habtm).
I have a +/- complex request forcing me to use a finder_sql because of that. More info here : http://stackoverflow.com/questio... :
[copy/paste:] " Hi,
I have a relationship table :
create_table "animal_friends", :force => 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 => 1 endlinking animals to others. Best way to retreive associations in SQL is :
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 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.
I'm currently using a finder_sql :
has_many :friends, :class_name => "Animal", :finder_sql => '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}'
but this method has the great disadvantage of breaking activerecord magic. For instance :
@animal.friends.firstwill execute the finder_sql without limit, fetching thousands of rows, then taking the first of the array (and loosing several precious seconds / req).
I guess it's a missing feature from AR, but I'd like to be sure first :) Thanks "
-
Santiago Pastorino
- State changed from new to open
- Importance changed from to
This issue has been automatically marked as stale because it has not been commented on for at least three months.
The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.
Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.
-
Santiago Pastorino
- State changed from open to stale
