2009-07-09 118 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除了您正在查询的图像外壳之外,还有一个图像外壳。