【问题标题】:How do I incorporate a "matching feature" in rails activerecord relationship如何在 rails activerecord 关系中加入“匹配功能”
【发布时间】:2021-02-09 18:35:47
【问题描述】:

我目前正在开发一个类似于 Tinder 等约会应用的项目。一个用户(在我的程序中名为 Owner)在其他所有者上滑动,如果他们都在彼此上滑动,它会创建一个“匹配”。我一直在寻找解决方案,例如类似于 Facebook 好友的好友请求。我看到人们使用布尔默认为 false 的“已确认”列并将其更改为 true,但我无法弄清楚这一点的逻辑。任何有关如何实现此目的的建议将不胜感激。我在这方面的唯一经验是追随者或追随者,不需要相互请求即可完成。

所有者类:(用户)

class Owner < ApplicationRecord
    has_many :matches
    has_many :friends, :through => :matches

 end

比赛类别:

class Match < ApplicationRecord
    belongs_to :owner
    belongs_to :friend, :class_name => "Owner"
end

感谢您的帮助!自联接对我来说是一个复杂的话题。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord self-join


    【解决方案1】:

    您可以向联接表中添加更多字段。您可以添加类似owner_acceptedfriend_accepted 的内容。虽然我认为只有一个accepted 字段就足够了。 示例解决方案:

    class AddAcceptedToMatches < ActiveRecord::Migration[6.0]
      def change
        add_column :matches, :accepted, :boolean, default: false
      end
    end
    
    class Owner < ApplicationRecord
      has_many :matches
      has_many :friends, :through => :matches
    
      def send_request_to(friend)
        friends << friend
      end
    
      def accept_request_from(owner)
        matches.find_by(owner_id: owner.id).accept
      end
    
      def is_friends_with?(stranger)
        match = matches.find_by(friend_id: stranger.id)
        return false unless match
        match.accepted?
    end
    
    class Match < ApplicationRecord
      belongs_to :owner
      belongs_to :friend, :class_name => "Owner"
    
      def accept
        update(accepted: true)
      end
    end
    

    然后您可以执行以下操作:

    owner = Owner.new
    friend = Owner.new
    
    owner.send_request_to(friend)
    owner.is_friends_with?(friend)
    # false
    friend.accept_request_from(owner)
    owner.is_friends_with?(friend)
    # true
    

    【讨论】:

    • 这让我走上了正轨,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多