我有一個Friends
模型與user_id
和friend_id
...都是id的特定用戶。協會通過非標準專欄?
我希望能夠做的是這樣的:
@relationship = Friend.find_by_user_id(current_user.id)
@relationship.friend.username
我在哪裏可以通過friend_id
列以同樣的方式,我可以做@relationship.user.username
基本上拉用戶。
我該如何設置我的關聯關閉?
我有一個Friends
模型與user_id
和friend_id
...都是id的特定用戶。協會通過非標準專欄?
我希望能夠做的是這樣的:
@relationship = Friend.find_by_user_id(current_user.id)
@relationship.friend.username
我在哪裏可以通過friend_id
列以同樣的方式,我可以做@relationship.user.username
基本上拉用戶。
我該如何設置我的關聯關閉?
使用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)