Ruby on rails 父关联上的条件作用域以获取所有子项

Ruby on rails 父关联上的条件作用域以获取所有子项,ruby-on-rails,ruby,ruby-on-rails-3.2,Ruby On Rails,Ruby,Ruby On Rails 3.2,我想把发表文章的所有评论都拿来。那么什么范围定义会给我结果呢。 文章模式 has_many :comments 注释模型 belongs_to :article 如果要将发布的值存储在布尔字段中,则可以在注释模型中定义这样的范围 scope :having_published_articles, joins(:article).where("articles.published=?", true) 可以用您正在使用的列名替换已发布 然后获取所有发表文章的评论: Comment.having

我想把发表文章的所有评论都拿来。那么什么范围定义会给我结果呢。 文章模式

has_many :comments
注释模型

belongs_to :article

如果要将发布的值存储在布尔字段中,则可以在注释模型中定义这样的范围

scope :having_published_articles, joins(:article).where("articles.published=?", true)
可以用您正在使用的列名替换已发布

然后获取所有发表文章的评论:

Comment.having_published_articles

如果要将发布的值存储在布尔字段中,则可以在注释模型中定义这样的范围

scope :having_published_articles, joins(:article).where("articles.published=?", true)
可以用您正在使用的列名替换已发布

然后获取所有发表文章的评论:

Comment.having_published_articles

如果要在所有Ruby中执行此操作,而不使用字符串,则如下所示:

scope :having_published_articles, joins(:article).where(articles: { state: 'published' })

如果要在所有Ruby中执行此操作,而不使用字符串,则如下所示:

scope :having_published_articles, joins(:article).where(articles: { state: 'published' })

default\u范围:publish,where(published:true)
Article.publish.comments
@RajarshiDas,它不应该是
default\u范围
,只应该是
scope
。未定义的方法“comments”用于#
范围:publish\u注释,包括(:Article)。where(published:true)
默认范围:publish,where(published:true)
Article.publish.comments
@RajarshiDas,它不应该是
默认范围
,而应该是
范围
。未定义的方法` comments'用于#
范围:publish\u comments,包括(:Article)。其中(published:true)
使用
包含
尽管有
连接
@RajarshiDas:如果还需要相关文章,则必须使用包含。但仅对于注释,应使用联接。尽管存在联接,但如果还需要关联的项目,则必须使用联接。但仅对于注释,应使用联接