【问题标题】:Rails - Two-way "friendship" model (cont'd)Rails - 双向“友谊”模型(续)
【发布时间】: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。

谢谢!

汤姆

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

railscasts episode关于这个话题

【讨论】:

  • 这看起来很有希望。谢谢。
【解决方案2】:

你不能在这里只使用@user.friendships,因为它只会给你那些@friendship.user_id == @user.id 的友谊。 我现在唯一能想到的就是去做

Friendship.find_by_user_id(@user.id).concat Friendship.find_by_friend_id(@user.id)

【讨论】:

    【解决方案3】:

    我的解决方案是一个范围:

    # model
    class Message < ActiveRecord::Base
      belongs_to :sender, :class_name => "User"
      belongs_to :recipient, :class_name => "User"
    
      scope :of_user, lambda { |user_id| where("sender_id = ? or recipient_id = ?",
            user_id,  user_id) }
    end
    
    
    # in controller
    @messages = Message.of_user(current_user)
    

    【讨论】:

      【解决方案4】:

      来自 railscast 链接:

      # models/user.rb
      has_many :friendships
      has_many :friends, :through => :friendships
      has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
      has_many :inverse_friends, :through => :inverse_friendships, :source => :user
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 2011-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多