【问题标题】:Rails calculate in whereRails 在哪里计算
【发布时间】:2013-08-21 13:26:01
【问题描述】:

我的应用有包含价格和计数列的项目表。 我需要显示价格乘以计数>而不是某个数字的项目列表。 现在我的代码是这样的

items.where("count * price >= 100")

我可以改变它吗?对任何变体感兴趣。 谢谢

【问题讨论】:

  • 感谢您的回答,但我需要商品清单,其中计数 * 价格 >= 100 =) 不是计数
  • 你有没有试过我帖子的第一个查询?
  • SQLite3::SQLException:靠近“*”:语法错误:
  • 您必须更准确地了解此错误,您可以发布完整的错误消息吗?
  • ActiveRecord::StatementInvalid in ItemsController#show SQLite3::SQLException: near "": syntax error: SELECT items., COUNT(items.*) AS count, (count * items.price) AS total FROM "items" WHERE (total >= 100) ORDER BY "items"."id" ASC LIMIT 1

标签: ruby-on-rails activerecord where


【解决方案1】:

如果你需要重复使用这个计算,你可以选择它并给它一个 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)

【讨论】:

    猜你喜欢
    • 2013-09-22
    • 2011-01-19
    • 2022-10-23
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多