Ruby on rails 关联的ActiveRecord条件(Rails)

Ruby on rails 关联的ActiveRecord条件(Rails),ruby-on-rails,activerecord,named-scope,Ruby On Rails,Activerecord,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.comments(或self.comments)放在:conditions散列中,该散列需要符号

class Post < ActiveRecord::Base
     has_many :comments
     named_scope :with_comments, :conditions => [#self.comments.length > 0]
end
class Post[#self.comments.length>0]
结束
我在评论区写什么


谢谢

您应该能够根据注释表进行连接,确保选择不同的行

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'

您应该能够根据注释表进行连接,确保选择不同的行

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'

最好在Post上放置计数器缓存

class Comment < AR:Base
  belongs_to :post, :counter_cache => true
end
类注释true
结束
那么您只需要执行一个查询,而不是两个查询


Post.find(:all,:conditions=>[“counter\u cache>0”])

最好在Post上放置一个counter\u cache

class Comment < AR:Base
  belongs_to :post, :counter_cache => true
end
类注释true
结束
那么您只需要执行一个查询,而不是两个查询


Post.find(:all,:conditions=>[“counter\u cache>0”])

看起来很棒。如何传入允许手动输入属性名称的参数。我的posts表有一个名为postid的pk,comments表有一个名为post_id的fk。我知道如何在关联中手动设置pks和fks,如何使用命名的_范围?再次感谢,这确实是一个高质量的响应。只需将:joins选项替换为所需的join即可。您可能需要如下内容:joins=>'internaljoin“comments”ON comments.post\u id=posts.postd'在Rails中,
:joins
默认使用
内部连接
看起来很棒。如何传入允许手动输入属性名称的参数。我的posts表有一个名为postid的pk,comments表有一个名为post_id的fk。我知道如何在关联中手动设置pks和fks,如何使用命名的_范围?再次感谢,这确实是一个高质量的响应。只需将:joins选项替换为所需的join即可。您可能需要如下内容:joins=>'internaljoin“comments”ON comments.post\u id=posts.postd'In Rails,
:joins
默认使用
内部连接