使用非常规列名称加入表

时间:2013-02-16 14:55:31

标签: ruby-on-rails rails-activerecord

我有以下型号:

class SocUser < ActiveRecord::Base
  attr_accessible :email, :id, :name, :username
  has_many :friends, :class_name => 'SocFriend', :foreign_key => 'user_id', :dependent =>  :destroy
  has_many :ownlist, :class_name => 'SocOwnlist', :foreign_key => 'user_id', :dependent =>  :destroy
end

class SocFriend < ActiveRecord::Base
  attr_accessible :user_id, :friend_id
  belongs_to :user, :class_name => 'SocUser'
  belongs_to :friend, :class_name => 'SocUser'
end

class SocOwnlist < ActiveRecord::Base
  attr_accessible :user_id, :book_id
  belongs_to :user, :class_name => 'SocUser'
  belongs_to :book, :class_name => 'SocBook'
end

用户可以拥有很多朋友。每个朋友也是一个用户。任何用户都可以拥有多本书。如何添加关联以便用户可以访问其朋友的所有书籍。

如果我在SocUser中添加关联,例如has_many :avail_list, :class_name => 'SocOwnlist', :through => :friends, :source => :friend

我们调用myuser.avail_list时生成的sql查询是:

SELECT "soc_ownlists".* FROM "soc_ownlists" INNER JOIN "soc_friends" ON "soc_ownlists"."id" = "soc_friends"."friend_id" WHERE "soc_friends"."user_id" = 1

但是ON条件应该是“soc_ownlists”。“user_id” =“soc_friends”。“friend_id”,有没有办法指定它?

或者还有其他方法来指定关联吗?

1 个答案:

答案 0 :(得分:0)

您必须为关联设置primary_key

has_many :avail_list, :class_name => 'SocOwnlist', :through => :friends, :source => :friend, :primary_key => 'user_id'