Rails和Postgres:找到一个“好交易”的项目

时间:2013-08-14 19:54:25

标签: 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天内创建的所有Prices价格都低于Product的近期平均价格。

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

编辑:我应该提到 - 我想从Price模式实现此方法 - 也就是说,只需显示所有价格合理的价格,而不是产品的所有价格都是优惠。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

在ActiveRecord中使用named scopes,您可以使用合成来获得所需内容:

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

答案 1 :(得分:0)

试试这个:

class Product < ActiveRecord::Base
  attr_accessor :name

  def your_query
    prices.where('created_at >= ?', 30.days.ago).where('value < ?', average_price)
  end

  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
相关问题