Rails包括范围

时间:2014-10-02 11:08:56

标签: ruby-on-rails activerecord scope rails-activerecord

我有一个名为Author的模型。一位作者有很多文章。 文章有一个名为.published的范围:where(published:true)。

我想加载作者,发表文章。 我试过了:

Author.includes(:articles.published).find(params[:author_id])

但是这会引发错误:未定义的方法'已发布'。 有什么想法吗?

4 个答案:

答案 0 :(得分:31)

我认为最好的解决方案是:

class Author < ActiveRecord::Base 
    scope :with_published_articles, -> { includes(:articles).where(articles: { published: true}) }
end

或者您可以创建范围:

Author.with_published_articles.find(params[:author_id].to_s)

然后:

<tr>
  <td><font color="black">Time:</td>
  <td colspan = "2"><input type = "time" name = "time_hr"></td>
  </tr>

答案 1 :(得分:16)

我会在名为Author的{​​{1}}上指定范围,如下所示:

with_published_articles

这将解决您的问题,以便在scope :with_published_articles, -> { joins(:articles).merge(Article.published) } 模型上指定where(active: true),以防Author行为和published将来发生变化。

所以现在你可以打电话:

Article

答案 2 :(得分:2)

试试这段代码:

(\d{2}:) (\d{2}:) ([0-9,]+) -> (\d{2}:) (\d{2}:) ([0-9,]+)

您可以在此处找到有关上述示例的更多信息: includes api doc

答案 3 :(得分:0)

使用:

Error: You are using macOS 10.15.
We do not provide support for this pre-release version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's Github.
Discourse, Twitter or IRC. You are responsible for resolving any issues you experience, as you are running this pre-release version.

在Autor上定义范围

class Articles < ActiveRecord::Base 
    scope :published, -> { where(articles: {published: true}) }
end

class Author < ActiveRecord::Base 
    scope :with_published_articles, -> { joins(:articles).merge(Articles.published) }
end