2015-01-31 23 views
0

所以我有軌應用程序所有職位都顯示在/職位,這是我想要他們的地方。在那裏,我每頁有10個帖子。但是,隨着這個頁面 - 我想採取最後三個職位,並顯示他們在根頁面上的div。想要顯示主頁上的最後3個職位

不確定從哪裏開始。

感謝

+0

你最後三個帖子是什麼意思? – locoboy 2015-01-31 20:32:48

+0

這是一個照片網站。所以上傳的最後3張照片。 – user3561169 2015-02-04 08:18:29

+0

確實有幫助嗎? – 2015-02-06 23:08:00

回答

1

試試這個:

%div 
    -Post.last(3).each do |p| 
    %h1= p.title 
    %p= p.author 
    %p= p.content 

Post.last(3)返回最後3個職位,你要尋找的。希望這可以幫助。

p.s.你可能需要通過將Post.last(3)轉換成你的控制器中的一個變量(如@latest_posts = Post.last(3))並重復此操作來重構該變量。

+0

請注意'last'將按照升序返回結果。 – 2015-01-31 20:28:32

1

查找方法last將按照升序返回結果。如果您想按照降序排列created_at返回結果,請按以下方法處理(包括單元測試)。

應用程序/模型/ post.rb

class Post < ActiveRecord::Base 
    def self.recent(max = 3) 
    limit(max).order(created_at: :desc) 
    end 
end 

規格/型號/ post_spec.rb

RSpec.describe Post, type: :model do 
    describe ".recent" do 
    it "returns the most recent" do 
     first_post = Post.create(created_at: 3.days.ago) 
     second_post = Post.create(created_at: 2.days.ago) 
     third_post = Post.create(created_at: 1.day.ago) 

     result = Post.recent(2) 

     expect(result).to eq([third_post, second_post]) 
    end 
    end 
end 

在你的控制器(S):

@recent_posts = Post.recent 

在你看來:

<div id="recent-posts"> 
    <ul> 
    <% @recent_posts.each do |post| %> 
     <li><%= post.title %></li> 
    <% end %> 
    </ul> 
</div> 

如果要重用視圖代碼,請將其放入局部視圖中,然後在您的視圖中進行渲染。

+0

測試的寫法是假定每個帖子都是在一天之後創建的。測試不應該更一般化,通過測試以查看每個帖子的創建日期是否小於/大於彼此(取決於通過ASC/DESC進行排序)? – 2017-07-04 20:33:21

+0

這些'created_at'日期是任意的。測試的目的是確保'Post.recent'的預期輸出。在這種情況下,返回最近的帖子。你提到的粒度類型將是ActiveRecord中'order'的單元測試。 – 2017-07-04 21:01:58

相關問題