在Rails中匹配用户

时间:2014-05-04 17:37:04

标签: ruby-on-rails ruby activerecord

我认为这更像是一个ruby问题而不是rails问题,但我对如何根据ActiveRecord中的属性匹配用户感到困惑。这甚至可能更像算法,但我并不积极。

基本上我想检查用户是否关注他们的朋友,如果他们的朋友关注他们,那么他们都被设置为" true"对于"匹配的"布尔值。

所以你可以看到我的数据库是如何构建的,目前我的迁移看起来像这样:

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end
    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end
end

我想以某种方式检查&#34;如果follower_id和follow_id =彼此相反,则设置匹配&#39;真的&#34;但我不确定是否有更好的标准&#34;这样做的方式。任何建议将不胜感激!显然我对红宝石来说还是一个新手,所以这是我想要理解的障碍。

2 个答案:

答案 0 :(得分:0)

这样的事情如何测试两个方向

User.find(id).relationships.include?(User.find(followed_id))

答案 1 :(得分:0)

根据具体情况,您有2个解决方案:

您只有2个用户的ID:签入数据库与这些用户有2个关系(每个方向一个)

alice_id = ...
bob_id = ...
matched = Relationship.where(follower_id: [alice_id, bob_id], followed_id: [alice_id, bob_id]).count == 2  

您的2位用户拥有关注者列表:我认为您在has_many :followers类中有User之类的关系,并且已加载关系。因此,您不需要对数据库进行额外查询

alice_user = ...  # for example User.includes(:followers).find(alice_id)
bob_user = ...
matched = alice_user.followers.include?(bob_user) && bob_user.followers.include?(alice_user)