I have a User model that has many fights. Fight belongs to User.
There are two foreign keys in the fight table that reference back to the user PK -- challenger_id and challengee_id.
开发者_运维知识库The trick is how do I write the has_many association on the User model so that it returns fights where user_id = challenger_id or challengee_id?
I believe you should use two separated associations and create a method to return all fights. Isn't it possible someday you'll need to get only the fights
where some @user
was the challenger
?
I'd do this like the following:
class User < ActiveRecord::Base
has_many :fights_as_challenger, :foreign_key => :challenger_id,
:class_name => "Fight"
has_many :fights_as_challengee, :foreign_key => :challengee_id,
:class_name => "Fight"
def all_fights
self.fights_as_challenger + self.fights_as_challengee
end
end
精彩评论