我需要使用 Rails 获取上一个和下一个事件记录对象。我做到了,但不知道这样做是否正确。
我有什么:
Controller :
@product = Product.friendly.find(params[:id])
order_list = Product.select(:id).all.map(&:id)
current_position = order_list.index(@product.id)
@previous_product = @collection.products.find(order_list[current_position - 1]) if order_list[current_position - 1]
@next_product = @collection.products.find(order_list[current_position + 1]) if order_list[current_position + 1]
@previous_product ||= Product.last
@next_product ||= Product.first
产品模型.rb
default_scope -> {order(:product_sub_group_id => :asc, :id => :asc)}
所以,这里的问题是我需要去我的数据库并获取所有这些 id 才能知道谁是上一个和下一个。
尝试使用 gem order_query ,但它对我不起作用,我注意到它进入数据库并按该顺序获取所有记录,所以,这就是为什么我做了同样的事情但只获取了 id。
我找到的所有解决方案都是简单的订单查询。按 id 或优先级字段之类的东西排序。
最佳答案
在您的 Product
中写下这些方法模型:
class Product
def next
self.class.where("id > ?", id).first
end
def previous
self.class.where("id < ?", id).last
end
end
现在您可以在 Controller 中执行以下操作:
@product = Product.friendly.find(params[:id])
@previous_product = @product.next
@next_product = @product.previous
请尝试一下,但它没有经过测试。
谢谢
关于ruby-on-rails - Rails 获取上一个和下一个事件记录对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665804/