2013-05-20 33 views
1

我有一個Friends模型與user_idfriend_id ...都是id的特定用戶。協會通過非標準專欄?

我希望能夠做的是這樣的:

@relationship = Friend.find_by_user_id(current_user.id) 
@relationship.friend.username 

我在哪裏可以通過friend_id列以同樣的方式,我可以做@relationship.user.username基本上拉用戶。

我該如何設置我的關聯關閉?

回答

0

使用class_name如果列不反映該公約預期:

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, class_name: 'User' 
end 

注意,我修改了模型名Friendship,以更好地反映使用這種模式。另外,還可以使它更容易爲自己,如果您修訂User模型是這樣的:

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships 

    has_many :friendships_of, :class_name => 'Friendship', :foreign_key => :friend_id 
    has_many :friends_of, :through => :friendships_of, :source => :user 
end 

我們看到所有用戶的朋友:

current_user.friends.map(&:username) 

而要看到誰「friended」用戶:

current_user.friends_of.map(&:username)