单表的多个引用

时间:2011-07-12 01:41:58

标签: ruby-on-rails ruby activerecord

我已经看过几次引用这个问题,但没有太完整。我在使用单个模型的连接表时遇到问题。例如,假设我们有Users和Highfives。 Highfives将成为两个用户highfiving的连接表。所以我有这个:

class Highfive < ActiveRecord::Base
  belongs_to :user1,
             :class_name => "User"

  belongs_to :user2,
             :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :highfives
end

然而,有了这个,我无法做像User.find(1).highfives这样的事情,因为它会生成如下查询:

SELECT "highfives".* FROM "highfives" WHERE "highfives"."user_id" = 1

真的,我应该得到一个类似的查询:

SELECT "highfives".* FROM "highfives" WHERE "highfives"."user1_id" = 1 or "highfives"."user2_id" = 1

我想要这样做我需要以某种方式修改我的用户模型。但是我错过了什么?

感谢。

2 个答案:

答案 0 :(得分:1)

您需要在has_many语句中指定外键,否则Rails会认为它是user_id

class User < ActiveRecord::Base
  has_many :highfives, :foreign_key => :user1_id
end

当然,这仅适用于单个外键。在您的情况下,您可能需要一个实例方法:

class User < ActiveRecord::Base
  def highfives
    Highfive.where("user1_id = ? or user2_id = ?", id, id)
  end
end

或者,假设User无法让自己高兴:

class User < ActiveRecord::Base
  has_many :highfives1, :class => "Highfive", :foreign_key => :user1_id
  has_many :highfives2, :class => "Highfive", :foreign_key => :user2_id
  def highfives
    highfives1 + highfives2
  end
end

答案 1 :(得分:0)

在模型中指定:foreign_key。所以..

class Highfive < ActiveRecord::Base
  belongs_to :user1,
             :class_name => "User",
             :foreign_key => "user1_id"

  belongs_to :user2,
             :class_name => "User",
             :foreign_key => "user2_id"
end

class User < ActiveRecord::Base
  has_many :highfive1, 
           :class_name => "Highfive",
           :foreign_key => "highfive1_id"
  has_many :highfive2, 
           :class_name => "Highfive",
           :foreign_key => "highfive2_id"
end

Reference!