我有两个型号:
class User < ActiveRecord::Base has_and_belongs_to_many :groups end class Group < ActiveRecord::Base has_and_belongs_to_many :users end
我想要做一个范围(这对于效率和链接范围的能力很重要),返回不属于任何组的用户.
经过许多尝试,我没有做一个方法,而不是范围,这使得收集在User.all是丑陋和..不正确.
任何帮助?
也许第二个问题:
我设法做出一个范围,返回属于任何给定组的用户(以id的数组给出).
scope :in_groups,lambda { |g| { :joins => :groups,:conditions => {:groups => {:id => g}},:select => "DISTINCT `users`.*" # kill duplicates } }
它可以更好/漂亮吗?
(使用Rails 3.0.9)
解决方法@H_301_19@
您的隐式连接表将根据命名约定命名为groups_users.在数据库中确认一次.假设是:
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.*"
}
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.*" }