2

I have the following model :

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

A user can have many friends. And each friend is also a user. Any user can have many books. How do I add an association so that a user can access all the books of his friends.

If I add an association in SocUser like has_many :avail_list, :class_name => 'SocOwnlist', :through => :friends, :source => :friend

The sql query it generates when we call myuser.avail_list is:

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

But the ON condition should be "soc_ownlists"."user_id" = "soc_friends"."friend_id", is there a way to specify it?

Or is there any other way to specify the association?

4

1 回答 1

0

您必须为关联设置 primary_key

has_many :avail_list, :class_name => 'SocOwnlist', :through => :friends, :source => :friend, :primary_key => 'user_id'
于 2013-02-16T20:31:32.447 回答