Rails habtm and finding record with no association

和自甴很熟 提交于 2019-11-28 23:34:03
rubish

Your implicit join table would have been named groups_users based on naming conventions. Confirm it once in your db. Assuming it is:

In newer Rails version:

scope :not_in_any_group -> {
    joins("LEFT JOIN groups_users ON users.id = groups_users.user_id")
    .where("groups_users.user_id IS NULL")
}

For older Rails versions:

scope :not_in_any_group, {
    :joins      => "LEFT JOIN groups_users ON users.id = groups_users.user_id",
    :conditions => "groups_users.user_id IS NULL",
    :select     => "DISTINCT users.*"
}

If you convert from HABTM to has_many through (more flexible) association, then you can use something like this:

class Group < ActiveRecord::Base
  has_many :groups_users, dependent: :destroy
  has_many :users, through: :groups_users, uniq: true

  scope :in_groups, -> { includes(:groups_users).where(groups_users: {group_id: nil}) }
end

class User < ActiveRecord::Base
  has_many :groups_users, dependent: :destroy
  has_many :groups, through: :groups_users
end

class GroupsUser < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!