関連付けのActiveRecord条件(レール)
-
05-07-2019 - |
質問
has_many:commentsというモデルPostがあると仮定します。コメントのある投稿のみを表示するにはどうすればよいですか?
named_scopeにはある程度慣れていますが、Post.comments(またはself.comments)をシンボルを必要とする:conditionsハッシュに入れる方法がわかりません。
class Post < ActiveRecord::Base
has_many :comments
named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
コメント領域に何を書くのですか?
ありがとう!
解決
より良いのは、Postにcounter_cacheを配置することです。
class Comment < AR:Base
belongs_to :post, :counter_cache => true
end
その後、2つではなく1つのクエリを実行するだけです。
Post.find(:all、:conditions =&gt; [&quot; counter_cache&gt; 0&quot;])
他のヒント
コメントテーブルに対して結合するだけで、個別の行を選択するようにしてください
named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
所属していません StackOverflow