活动记录对象数组中的下一个元素

时间:2015-11-19 14:48:39

标签: 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(之前)适用于特定主题的任何帖子?

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

答案 1 :(得分:0)

尝试这样的事情:

some_topic.posts.where("id > ?", 74).order(:id).first

或者,如果您有一些主题(不确定您的型号),但它看起来与此类似:

74

此处$('#email_preview').click(function (event) { // <-- it should be 'event' btw event.preventDefault(); my_js_function("{{ form.modchoicfield }}"); // <-- no need for 'data' }); 是当前帖子的ID。

答案 2 :(得分:0)

有一些宝石值得帮助。我创建了一个退出灵活的,因为它可以动态地与任何集合及其顺序一起工作(当硬编码为Book.where("id > ?", 74).order(:id)时不是这种情况)

gem名为nexter,其基本用法如下:

@books = Book.includes(:author).bestsellers.
          order("genre", "authors.name", "published_at desc")

nexter = Nexter.wrap( @books, @books.find(params[:id]) )
nexter.previous
nexter.next

有关详细信息,请参阅README

相关问题