【发布时间】:2023-04-04 02:05:02
【问题描述】:
这是这个问题的延续: Original Question (SO)
这个问题的答案涉及以下一组模型:
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships #...
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'
end
<% for friendship in @user.friendships %>
<%= friendship.status %>
<%= friendship.friend.firstname %>
<% end %>
如果说,我有一个用户并且我想获得他或她的 id 是友谊模型上的 :user_id FK 的所有“友谊”,这很好用。但是,当我运行类似的东西时
@user.friendships.friends
我希望它返回该用户是友谊中的 :user 或 :friend 的所有用户记录 - 因此,换句话说,返回该用户参与的所有友谊。
希望以上内容有意义。我对 Rails 还是很陌生,希望有一种方法可以优雅地做到这一点,而无需仅制作标准链接表或提供自定义 SQL。
谢谢!
汤姆
【问题讨论】:
-
这里有一个很好的答案类似的问题:link table with foreign keys
标签: ruby-on-rails ruby