开发者

Multiple References From Single Table

I've seen this issue referenced a few times, but nothing too complete. I'm having a problem with using a join table for a single model. For example, suppose we have Users and Highfives. Highfives will just be a join table for the two users highfiving. So I have thi开发者_如何转开发s:

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

However, with this, I am unable to do something like User.find(1).highfives since that generates a query like:

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

Really, I should be getting a query like:

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

I imagine to do this I'll need to modify my User model in some way. But what am I missing?

Thanks.


You need to specify the foreign key in your has_many statement, otherwise Rails will assume it's user_id:

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

Of course, this only works for a single foreign key. In your case, you'd probably want an instance method instead:

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

Or, assuming it's impossible for a User to highfive himself:

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


Specify :foreign_key in your Models. So..

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!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜