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

标签 ruby-on-rails ruby activerecord

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/

相关文章:

ruby-on-rails - ActiveRecord 模型实例上的陈旧关联数据?

ruby-on-rails - ActiveRecord::InvalidForeignKey 错误

PHP Codeigniter Active Records 忽略单引号

ruby - ruby 中的 if 语句,以确定输入类型

ruby - 将 Ruby block 中的变量分配给更高的范围

用于查找二进制间隙的 Ruby 正则表达式

ruby-on-rails - Rails ActiveRecord 协会

ruby-on-rails - Guard 没有键盘输出

ios - 通过参数将数据从 Swift 中的 iOS 发送到 Rails 应用程序

ruby-on-rails - 从 Rails 发布到 Facebook 粉丝专页墙