2016-07-22 98 views
0

我爲我的最新帖子創建了一個部分,還爲所有帖子創建了一個部分。不過,我上次創建的帖子會顯示兩次。Rails:顯示除最新帖子外的所有帖子

在我的控制器中,如何顯示除最後一篇文章以外的所有文章?

MainController

def index 
     @post = Post.all.order('created_at DESC') 
     @latest_post = Post.ordered.first 
     end 

回答

3

你查詢兩次。相反,查詢一次,拉最新帖子不在結果集:

def index 
    @posts = Post.all.order('created_at DESC').to_a 
    @latest_post = @posts.pop 
end 

我不能完全確定你正在考慮的「第一」的記錄其結果的一側,因此,如果出現@posts.pop給你您認爲是「最後」記錄,然後使用@posts.shift從另一端刪除記錄。

+0

這不會取@latest_post我得到一個錯誤:'未定義的方法「pop'' - 我是新來的軌 – GVS

+0

@GVS固定,需要'to_a' – meagar

+0

將您的代碼放在我的控制器中。我在我的視圖代碼中出現了一個錯誤,該行使用了<%@ post.each do | post | %>'我刪除了我的視圖文件中的代碼,並且錯誤仍然顯示,即使代碼已被刪除。所以我重新啓動了我的服務器,錯誤仍然顯示。我用我的原始控制器代碼替換了你的控制器代碼,它再次工作。我不知道爲什麼會發生這種情況 – GVS

1

@post

def index 
    @latest_post = Post.ordered.first 
    @post = Post.where.not(id: @latest_post.id).order('created_at DESC') 
end 

或者乾脆

def index 
    @latest_post = Post.last 
    @posts = Post.where.not(id: @latest_post.id).order('created_at DESC') 
end 
相關問題