Ruby on rails 通过非标准列进行关联?
我有一个Ruby on rails 通过非标准列进行关联?,ruby-on-rails,associations,Ruby On Rails,Associations,我有一个Friends模型,带有user\u id和Friends\u id…这两个都是特定用户的id 我想做的是这样的事情: @relationship = Friend.find_by_user_id(current_user.id) @relationship.friend.username class User < ActiveRecord::Base has_many :friendships has_many :friends, :through => :fri
Friends
模型,带有user\u id
和Friends\u id
…这两个都是特定用户的id
我想做的是这样的事情:
@relationship = Friend.find_by_user_id(current_user.id)
@relationship.friend.username
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
在这里,我基本上可以通过friend\u id
列拉动用户,方法与@relationship.user.username
相同
我该如何设置关联以实现这一点?这不是一种多对多的情况吗 我认为这是一个完美的解决方案
希望这有帮助 如果您的列未反映预期的约定,请使用
class\u name
:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User'
end
现在查看用户的所有好友:
current_user.friends.map(&:username)
要查看谁与用户“交朋友”,请执行以下操作:
current_user.friends_of.map(&:username)