如何从 Rails 中的控制器过滤关联记录



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

我的观点如下所示:

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

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

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

可以轻松地过滤我视图中的评论:

<% @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)逻辑放在我的观点中。如何从控制器中筛选文章的评论?

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

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,道具给谢恩

最新更新