2
我的应用程序有列表价格和数量的项目表。 我需要显示价格乘以count>的项目列表。 现在我的代码看起来像这样Rails在哪里计算
items.where("count * price >= 100")
我可以改变它的东西吗?对任何变体感兴趣。 谢谢
我的应用程序有列表价格和数量的项目表。 我需要显示价格乘以count>的项目列表。 现在我的代码看起来像这样Rails在哪里计算
items.where("count * price >= 100")
我可以改变它的东西吗?对任何变体感兴趣。 谢谢
如果您需要重新使用这种计算,您可以选择它,并给它一个别名为SQL:
items = items.select('items.*, COUNT(items.*) AS count, (count * items.price) AS total').where('total >= 100')
然后直接使用总变量:
items.first.total # => Should return the count*price
items.first.count # => Should return the count
items.first.id # => You can call all the other attributes of an Item
你也可以做它的一个范围:
class Item < ActiveRecord::Base
scope :total_more_than, lambda do |total|
self.select('items.*, COUNT(items.*) AS count, (count * items.price) AS total').where('total >= ?', total || 100) # if not total given, will use 100
end
而且使用这样的:
items.total_more_than(100)
谢谢你的回答,但我需要的产品清单,其中数*价格> = 100 =),不计 –
您是否尝试过帖子的第一个查询? – MrYoshiji
SQLite3 :: SQLException:接近“*”:语法错误: –