【问题标题】:How to return the next record?如何返回下一条记录?
【发布时间】:2013-12-04 12:28:55
【问题描述】:

在我的 Rails 应用程序中,我有一个函数 next,我在 show 模板中使用它来链接到下一个 product(由 price 排序):

class Product < ActiveRecord::Base 

  belongs_to  :user

  def next
    Product.where("user_id = ? AND price > ?", user_id, price).order("price ASC").first 
  end

end

问题在于,此功能仅在所有产品具有不同价格时才有效。当有多个价格相同的产品时,next 函数会随机选择一种产品 (?) 从而跳过所有其他产品。

有没有办法让这个函数返回下一个产品,即使它具有相同的价格? (如果价格相同,可以简单地按ID或日期订购产品)

我尝试将&gt; 替换为&gt;=,但没有成功。

感谢您的帮助。

【问题讨论】:

  • 你可以试试这个self.class.first(:conditions =&gt; ['id &gt; ?', self.id], :limit =&gt; 1, :offset =&gt; 0, :order =&gt; "id ASC")
  • 下一条记录是指成本高于这个但在该组中排名第一的产品吗?例如:P1-10,P2-12,P3-9,P4-11..P1 的下一个是 P4 是吗?

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


【解决方案1】:

您必须在where 子句和order 中使用id

  def next
    Product.where("user_id = ? AND price >= ? AND id > ?", user_id, price, id).order("total, id").first 
  end

【讨论】:

  • 我想你忘记了, id。不?无论如何,这不起作用,因为它会忽略具有较高 price较低 id 的产品。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2018-03-15
  • 2016-05-22
  • 2018-09-13
  • 2017-10-14
相关资源
最近更新 更多