开发者

has_many, belongs_to association where has_many associated model has two alias fk in belongs_to associated_model

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜