11

我有2種型號:的Rails的habtm並沒有關聯找到記錄

class User < ActiveRecord::Base 
    has_and_belongs_to_many :groups 
end 

class Group < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

我想打一個範圍(這一點很重要 - 對效率和能力鏈範圍),返回那並不是用戶t屬於ANY羣組。 多次嘗試後,我在做的方法,而不是範圍,這使得collectUser.all這是醜陋..不對的失敗。

任何幫助?

也許對於第二個問題: 我設法創建一個範圍,返回屬於任何給定組的用戶(作爲ID數組給出)。

scope :in_groups, lambda { |g| 
     { 
      :joins  => :groups, 
      :conditions => {:groups => {:id => g}}, 
      :select  => "DISTINCT `users`.*" # kill duplicates 
     } 
     } 

它可以更好/更漂亮嗎? (使用Rails 3.0.9)

回答

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") 
} 

對於舊的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.*" 
} 
+0

謝謝,它訣竅:) – schiza

+1

你需要DISTIN CT在這種情況下將不存在返回結果的連接關係,因此不會重複用戶? –

+0

'DISTINCT'不需要。我添加了Rails 4及更高版本所需的新語法(我認爲)。 – slhck

2

如果從HABTM轉換到(更靈活)協會HAS_MANY,那麼你可以使用這樣的事情:

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 
相關問題