Ruby on Rails 下一篇/上一篇文章
我有一个索引页面 - posts#index,其中包含指向每个帖子的显示页面的链接。每个帖子都引用一个特定的主题,并且可能是在不同的时间创建的,因此帖子的 id 对于该主题中的所有帖子来说不一定是连续的。我希望能够转到特定主题的下一篇和上一篇文章。
在我的 PostsController 中,我有一个主题的所有帖子的实例变量和正在显示的特定主题
def index
@topic = Topic.find(params[:topic_id])
@posts = @topic.posts.all
end
def show
@topic = Topic.find(params[:topic_id])
@posts = @topic.posts.all
@post = @topic.posts.find(params[:id])
end
@posts 是一个事件记录对象数组
@posts => #<ActiveRecord::AssociationRelation [
#<Post id: 73, topic_id: 3>,
#<Post id: 74, topic_id: 3>,
#<Post id: 76, topic_id: 3>,
#<Post id: 77, topic_id: 3>,
#<Post id: 91, topic_id: 3>]
如果这是一个 ruby 对象数组,我可以使用 @posts.index(@post)
查找数组特定元素的 ID,然后执行 index + 1
或 index - 1
遍历帖子数组,但是 .index
是事件记录中的另一种方法。如果我在特定主题的任何给定帖子的显示页面上,Post id: 76
例如,我怎样才能去 link_to Post id: 74
(下一个)和 link_to Post id: 77
(上一个)以适用于特定主题的任何帖子的方式?
最佳答案
您可以简单地执行以下操作:
def show
@topic = Topic.find(params[:topic_id])
posts = @topic.posts.order('posts.id ASC')
@post = posts.find(params[:id])
@previous_post = posts.where('posts.id < ?', @post.id).first
@next_post = posts.where('posts.id > ?', @post.id).first
end
关于ruby-on-rails - 事件记录对象数组中的下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33807083/