2016-07-22 101 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 
相关问题