2

Rails アプリケーションには 2 つのモデルがあり、さまざまなショップでの製品の価格を追跡しています。ここにそれらがありますが、単純化されています:

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その製品の現在の平均を下回るすべてのオブジェクトを検索したいと考えています。これは基本的Pricesに、過去 30 日間に作成されたもので、その価格が最近の平均価格を下回っていることを意味しProductます。

これは可能ですか?Postgresを使用しています。

編集:私は言及する必要がありました-モデルからこのメソッドを実装したいPrice-つまり、お得な製品のすべての価格ではなく、お得なすべての価格を表示できるようにするだけです。

助けてくれてありがとう!

4

2 に答える 2

1

Using named scopes in ActiveRecord, you can use composition to get what you want:

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
于 2013-08-14T20:31:51.917 に答える