협회의 Activerecord 조건 (Rails)
-
05-07-2019 - |
문제
has_many : comment. 주석이있는 게시물 만 표시하려면 어떻게해야합니까?
나는 named_scope에 대해 다소 편안하지만 : post.comments (또는 self.comments)를 다음에 넣을 수있는 방법을 모르겠습니다. 기호를 기대하는 조건 해시.
class Post < ActiveRecord::Base
has_many :comments
named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
주석은 영역에 무엇을 써야합니까?
감사!
해결책
게시물에 Counter_Cache를 넣는 것이 좋습니다.
class Comment < AR:Base
belongs_to :post, :counter_cache => true
end
그런 다음 2 개 대신 1 개의 쿼리 만 수행하면됩니다.
Post.find(:all, :conditions => ["counter_cache > 0"])
다른 팁
주석 테이블에 가입하여 고유 한 행을 선택해야합니다.
named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
제휴하지 않습니다 StackOverflow