我有一个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)