在我的博客应用程序中,我可以拨打
@article.comments.last
。如何创建一个 next_comment
方法,该方法 always 选择行中的下一条评论?
更新: 另外,我该如何做相反的事情,定义一个
previous_comment
方法?
更新下面的答案。
之前记录:
class Comment < ActiveRecord::Base
def self.previous(comment, key = :id)
self.where("#{key} < ?", commend.send(key)).first
end
end
为了定义“下一个”,您必须声明一个排序规则。没有订单就没有“下一个”。
顺序可以很简单,例如通过主键或其他字段(例如名称)。以下方法应该支持这两种情况,并且默认为“id”
class Comment < ActiveRecord::Base
def self.next(comment, key = :id)
self.where("#{key} > ?", comment.send(key)).first
end
end
您应该在链上调用它并传递评论实例,以便它可以使用与加载原始评论相同的关系
scope = @article.comments
last = scope.last
next = scope.next(last)
另一个(也许更简单)的解决方案是简单地加载两个对象
current, next = @article.comments.take(2)
你也可以把它变成一个方法
class Comment < ActiveRecord::Base
def self.first_and_next
# use all to create a scope in case you call
# the method directly on the Comment class
all.take(2)
end
end
current, next = @article.comments.first_and_next(2)
鉴于您有一个分页宝石,例如
will_paginate
,这将起作用
# Article model
def next_comment
@page ||= 0
@page += 1
comments.page(@page).per(1).first
end
或者如果你不想存储状态
# Comment model
def next_comment
article.comments.where("id > ?", id).first
end
脏溶液:
class Comment < ActiveRecord::Base
def next_comment
article.comments.where('id > ?', id).first
end
end