2009-07-09 15 views
0

ImageShellsとUsersの間にmany_to_manyの関係があります。私は、ユーザーがいないすべてのImageShellを見つける必要があります。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は、実際のユーザーせずに画像の殻を見つけることができません。それは実際にそのデータベース内のすべてのユーザーに画像の殻を結合あなたが照会しているイメージシェル以外のイメージシェルを持っています。

関連する問題