2016-02-29 47 views
1

我有兩個模型,ArticleComment與一對多的關係。如何在Rails中過濾來自控制器的相關記錄?

我的看法是這樣的:

<% @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)邏輯放在我的vi裏EW。我如何從控制器內過濾文章的評論?

+0

我已經編輯你的問題根據你的意見。如果出現錯誤,遺漏或不清楚,請隨時更改。 – Stefan

+0

你完美地編輯了我的朋友! – Liroy

回答

3

你可以做這樣的事情在模型

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,道具巴蒂爾

+0

我很喜歡這個邏輯。然而,我得到'未知的關鍵::訂單' – Liroy

+1

編輯。看起來我參考的答案有點過時了。您也不需要按順序指定'ASC',因爲它是默認選項。 – fgperianez

+0

謝謝!這工作。 – Liroy

相關問題