如何找到价格最高的记录?
这将返回最大值值,而不是完整的记录:
self.prices.maximum(:price_field)
目前,我找到这样的记录:
def maximum_price
self.prices.find(:first, :conditions => "price = #{self.prices.maximum(:price_field)}" )
end
这是正确的方法吗?因为上面需要两条SQL语句才能工作,而且感觉不太对劲。
Ps。此外,我希望如果多个记录具有相同的“最大值”值,那么它应该获取具有最新 updated_at
值的记录。那么这意味着另一个 SQL 语句?
Pps。有谁知道 Rails 中关于 AREL 和非 AREL 事物的好的或详细的参考吗? Rails Guide for ActiveRecord 查询还不够!
(我正在使用 Rails 3)
===更新===
使用 AREL 我执行以下操作:
self.prices.order("updated_at DESC").maximum(:price_field)
但这仅给出最大值,而不是完整记录:(
另外,maximum()的使用真的是AREL吗?
This returns the maxium value, not the complete record:
self.prices.maximum(:price_field)
And currently, I find the record like this:
def maximum_price
self.prices.find(:first, :conditions => "price = #{self.prices.maximum(:price_field)}" )
end
Is this the correct way ? Because the above needs two SQL statements to make it work, and it somehow does not feel right.
Ps. Additionally, I want that if more than one record has the same "maximum" value, then it should get the one with the latest updated_at
value. So that would mean another SQL statement??
Pps. Does anyone know of a good or detailed reference for AREL and non-AREL things in Rails? The Rails Guide for ActiveRecord query is just not enough!
(I'm using Rails 3)
===UPDATE===
Using AREL I do the following:
self.prices.order("updated_at DESC").maximum(:price_field)
But this only gives the maximum value, not the complete record :(
Also, is the use of maximum()
really AREL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的事情怎么样?
How about something like this?