【问题标题】:Rails - ActiveRecord - Find Common Group Based on CommonalitiesRails - ActiveRecord - 根据共同点查找共同组
【发布时间】:2014-02-10 23:38:30
【问题描述】:

假设我有以下模型:

Group
  has_many :users

User
  belongs_to :group

我有以下表格:

   User_id                    Group
  -------------------------------------
    1                        Police
    2                        Fire
    3                        Military
    4                        Police
    5                        Police
    1                        Fire

大多数用户属于一个组,但有些用户,例如user_id: 1 属于多个组。 (他属于PoliceFire

我的问题是:如果给我两个user_id's,(比如12),我将如何查询以找出这两个用户所属的共同组(例如,在上述情况下,查询将返回Fire

希望这是有道理的。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    首先,我建议在用户和组之间使用 has_and_belongs_to_many 关系:

    class Group
        has_and_belongs_to_many :users
    end
    
    class User
        has_and_belongs_to_many :users
    end
    

    你会有这样的表格:

    create_table "groups", force: true do |t|
        t.string name
    end
    
    create_table "users", force: true do |t|
        ...
    end
    
    create_table "groups_users", id: false, force: true do |t|
        t.integer "group_id"
        t.integer "user_id"
    end
    

    这将防止您当前在组表中的组字段中进行重复。它还有助于避免某些数据输入错误(拼写错误)并使构建更好的 UI 变得更容易。还有其他方法可以克服这些相同的障碍,但它们比通常不遵守约定所节省的努力要多得多。

    然后你可以得到两个用户(user_a 和 user_b)的组的交集,比如:

    user_a.groups & user_b.groups # => an array of the groups that they both belong to
    
    (user_a.groups & user_b.groups).collect(&:name) # => an array of the names of the groups they both belong to.
    

    【讨论】:

      【解决方案2】:

      这实际上取决于您的关联是如何设置的,但这是在一个查询中执行此操作的一种方法

      user_a.groups.where(id: user_b.groups.select(:id))
      

      【讨论】:

        猜你喜欢
        • 2011-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-19
        相关资源
        最近更新 更多