【问题标题】:has_many, belongs_to association where has_many associated model has two alias fk in belongs_to associated_modelhas_many,belongs_to 关联,其中 has_many 关联模型在 belongs_to associated_model 中有两个别名 fk
【发布时间】:2010-06-19 10:54:37
【问题描述】:

我有一个有很多战斗的用户模型。战斗属于用户。

战斗表中有两个外键引用回用户PK——challenge_id和challenge_id。

诀窍是如何在 User 模型上编写 has_many 关联,以便它返回 user_id = challenger_id 或 challengee_id 的战斗?

【问题讨论】:

  • 猜猜这比想象的要简单:has_many :fights, :foreign_key => 'challenge_id or challengee_id'

标签: ruby-on-rails associations foreign-key-relationship has-many belongs-to


【解决方案1】:

我相信你应该使用两个独立的关联并创建一个返回所有战斗的方法。难道有一天你只需要得到fights,其中一些@userchallenger吗?

我会这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多