2009-07-09 117 views
0

我在ImageShells和Users之間有many_to_many關係。我需要找到所有沒有用戶的ImageShells。ActiveRecord:找不到關聯

我有一個查詢,發現他們,但我怎麼把這個到named_scope

SELECT * FROM image_shells INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id) 


class ImageShell < ActiveRecord::Base 
    has_and_belongs_to_many :riders, :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :image_shells 
end 

我可以使用查找sql​​,但這是混亂。

img_shells_with_out_users = ImageShell.find_by_sql 'SELECT * FROM image_shells INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id)' 

回答

8

應該做的生成所有正確的,當使用包括選擇加入爲你的伎倆

named_scope :without_users, { :include => :users, 
    :conditions => 'image_shell_users.user_id IS NULL' } 

ActiveRecord的照顧。爲了包含用戶必須通過連接表,所以你可以在你的條件下使用它。

1

超級簡單

named_scope :with_out_users, { 
:select => "image_shells.*", 
:joins => "INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id)" 
    } 
0
named_scope :without_users, 
    :conditions => "not exists (select * from image_shells_users where 
        image_shell_users.image_shell_id = image_shells.id)" 

您的問題提供實際上並不沒有找到用戶的圖像彈它實際上加入了圖像殼用戶在數據庫中的SQL除了您正在查詢的圖像外殼之外,還有一個圖像外殼。