sch*_*iza 12 activerecord ruby-on-rails associations has-and-belongs-to-many
我有2个型号:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
Run Code Online (Sandbox Code Playgroud)
我想创建一个范围(这对于效率和链接范围的能力很重要),它返回不属于任何组的用户.多次尝试后,我在做的方法,而不是范围,这使得失败collect
的User.all
是丑陋和..不正确的.
有帮助吗?
也许对于第二个问题:我设法创建一个范围,返回属于任何给定组的用户(作为id的数组给出).
scope :in_groups, lambda { |g|
{
:joins => :groups,
:conditions => {:groups => {:id => g}},
:select => "DISTINCT `users`.*" # kill duplicates
}
}
Run Code Online (Sandbox Code Playgroud)
可以更好/更漂亮吗?(使用Rails 3.0.9)
rub*_*ish 17
您的隐式连接表将groups_users
根据命名约定命名.在数据库中确认一次.假设它是:
在较新的Rails版本中:
scope :not_in_any_group -> {
joins("LEFT JOIN groups_users ON users.id = groups_users.user_id")
.where("groups_users.user_id IS NULL")
}
Run Code Online (Sandbox Code Playgroud)
对于较旧的Rails版本:
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.*"
}
Run Code Online (Sandbox Code Playgroud)