2011-01-01 2 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

더 좋은 방법이 있습니까? 이로 인해 하나의 쿼리가 데이터베이스에 적용됩니다. 나는 5,000 기록이 태그와 같은이 용납 할 수있다. – 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

두 가지 언급 : a) SQL 코드에서 'single'을 사용해야합니다. MySQL은 " '"과 ""'같은 것을 취급하지만 다른 데이터베이스 (예 : PostgreSQL)는 그렇지 않습니다 .b) 그걸 가지고 놀지 않고서 - 왜이 코드를 쇠사슬로 묶지 않을 수 있습니까? – radiospiel

4

다음은 나를 위해 작동하는 것 같다 :

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

이뿐만 아니라 체인을 지원해야한다. 예를 들어 다음과 같이 작동해야합니다.

Entry.includes("taggings").where("taggings.id is null").where(foo: "bar") 
관련 문제