【问题标题】:How to filter associated records from controller in Rails?如何从 Rails 中的控制器过滤关联记录?
【发布时间】:2016-02-29 13:03:03
【问题描述】:

我有两个模型,ArticleComment 具有一对多关系。

我的观点是这样的:

<% @articles.each do |article| %>
  <% article.comments.each do |comment| %>
    some content
  <% end %>
<% end %>

很容易从控制器中过滤@articles,例如:

@articles = Article.order('created_at asc').last(4)

而且我可以轻松过滤我认为的 cmets:

<% @articles.each do |article| %>
  <% article.comments.order('created_at asc').last(4).each do |comment| %>
    some content
  <% end %>
<% end %>

但我不想将order('created_at asc').last(4) 逻辑放在我的视图中。如何从控制器中过滤文章的 cmets?

【问题讨论】:

  • 我已根据您的 cmets 编辑了您的问题。如果有问题、缺失或不清楚,请随时更改。
  • 你编辑得很好我的朋友!

标签: ruby-on-rails ruby controller


【解决方案1】:

你可以在模型中做这样的事情

Class Article < ActiveRecord::Base
  has_many :comments, -> { order 'created_at' } do
    def recent
      limit(4)
    end
  end
end

然后在视图中按如下方式使用

@articles.each do |article| 
    article.comments.recent.each do |comment|
        stuff
    end
end

来源:https://stackoverflow.com/a/15284499/2511498,Shane 的道具

【讨论】:

  • 我非常喜欢这个逻辑。但是,我得到Unknown key: :order
  • 已编辑。看起来我作为参考的答案有点过时了。此外,您不需要按顺序指定“ASC”,因为它是默认选项。
猜你喜欢
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2011-07-13
  • 2017-04-19
相关资源
最近更新 更多