ruby-on-rails - Rails 和 Postgres : Finding items that are a "good deal"

标签 ruby-on-rails ruby postgresql activerecord

我的 Rails 应用程序中有两个模型,用于跟踪不同商店的产品价格。它们在这里,但经过简化:

class Product < ActiveRecord::Base
    attr_accessor :name

    def latest_prices
        prices.where('created_at >= ?', 30.days.ago)
    end

    def average_price
        latest_prices.prices.map(&:value).sum / latest_prices.count
    end
end

class Price < ActiveRecord::Base
    attr_accessor :value, :shop_name, :created_at
    belongs_to :product
end

我现在想找到低于该产品当前平均价格的所有 Price 对象。这基本上意味着过去 30 天内创建的所有价格,其价格低于该产品的近期平均价格。

这可能吗?我正在使用 Postgres。

编辑: 我应该提到 - 我想从 Price 模型中实现这个方法 - 也就是说,只能够显示所有很划算的价格,而不是划算的产品的所有价格。

在此先感谢您的帮助!

最佳答案

使用 named scopes在 ActiveRecord 中,你可以使用组合来获得你想要的:

class Product < ActiveRecord::Base
  attr_accessor :name
  has_many :prices
end

class Price < ActiveRecord::Base
  attr_accessor :value, :shop_name, :created_at
  belongs_to :product

  scope :latest, where('created_at >= ?', 30.days.ago)
  scope :less_than, lambda { |value| where("value < ?", value) }

  def good_deals
    latest.less_than(average('value'))
  end

end

关于ruby-on-rails - Rails 和 Postgres : Finding items that are a "good deal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18241054/

相关文章:

ruby-on-rails - Rails 未初始化常量名称错误

javascript - 文件上传无照片参数问题

ruby-on-rails - 在 where 子句中减去

ruby-on-rails - 如何使 Ruby 模型查找,为整数列选择返回整数?

sql - 如何从 3 个表中选择特定数据? [PostgreSQL 9.1]

ruby-on-rails - 如何在前台阻止 dockerized nginx 泛滥日志?

ruby-on-rails - Gem::Installer::ExtensionBuildError: 错误:无法构建 gem native 扩展 ubuntu

ruby - 是什么导致我的 Ruby `trap` block 出现这种死锁?

php - Doctrine 多对多关系

sql - 查找 PostgreSQL 中两个大表之间的差异