2011-01-01 13 views

答えて

0

act-as-taggable-onの内部を知らなくても、クエリや生のSQLをループすることを含まないきれいな方法は考えられません。これは読み取り可能です:

need_to_tag = [] 

Entry.all.each do |e| 
    need_to_tag << e if e.tag_list.blank? 
end 

need_to_tagは、タグなしエントリを保持します。

+0

ありがとうございます。私はもっ​​と良い方法があることを望みましたが、これも確かに機能します。 –

+0

より良い方法はありますか? 1つのクエリがデータベースにヒットします。私は5000レコードがタグ付けされており、これは容認できないものがあります。 – David

+0

私はあなたにとって最良の方法は、その場合に生のSQLクエリを使うことになると思います。 – stef

1

私はこれが古代であることを理解していますが、私は今日も同様の必要性に迫っています。

scope :untagged, lambda { 
    # first build a scope for the records of this type that *are* tagged 
    tagged_scope = Tagging.where(:taggable_type => base_class.to_s) 

    # only fetching the taggable ids 
    tagged_scope = tagged_scope.select('DISTINCT taggable_id') 

    # and use it to retrieve the set of ids you *don't* want 
    tagged_ids = connection.select_values(tagged_scope.to_sql) 

    # then query for the rest of the records, excluding what you've found 
    where arel_table[:id].not_in(tagged_ids) 
} 

それは巨大なデータセットのための効率的ではないかもしれないが、それは私の目的に合った:私は、単純な複数のクエリスコープでそれをやりました。

2

タグ付きの写真とタグの付いていない写真を見つける方法は次のとおりです。

scope :with_taggings, where('id in (select taggable_id from taggings where taggable_type = ’Photo‘ and context = ’bibs‘)') 
scope :without_taggings, where('id not in (select taggable_id from taggings where taggable_type = ’Photo‘ and context = ’bibs‘)') 

しかし、これはフォトモデルでは機能しますが、他のスコープではチェーンできません。

+0

2つの注意点:a)SQLコードでは 'single'を使用する必要があります。 MySQLは "'"と ""'同じものを扱いますが、他のデータベース(PostgreSQLなど)はそうではありません。 – radiospiel

4

以下は私のために働くようだ:

Entry.includes("taggings").where("taggings.id is null") 

これは、同様の連鎖サポートする必要があります。たとえば、次のように動作します。

Entry.includes("taggings").where("taggings.id is null").where(foo: "bar") 
関連する問題