gpt4 book ai didi

ruby-on-rails - 事件记录对象数组中的下一个元素

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:35 24 4
gpt4 key购买 nike

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 + 1index - 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com