Ruby on rails 3 价格的活动记录嵌套属性

Ruby on rails 3 价格的活动记录嵌套属性,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,我是一名全新的rails开发人员,请耐心等待:-) 在rails中,我有两个名为Product和ProductPrice的模型 以下是ProductPrices的外观: class CreateProductPrices < ActiveRecord::Migration def change create_table :product_prices do |t| t.integer :product_id t.date :since t.d

我是一名全新的rails开发人员,请耐心等待:-)

在rails中,我有两个名为Product和ProductPrice的模型

以下是ProductPrices的外观:

class CreateProductPrices < ActiveRecord::Migration
  def change
    create_table :product_prices do |t|
      t.integer :product_id
      t.date :since
      t.decimal :price
      t.boolean :current

      t.timestamps
    end
  end
end

然后它完全符合我在问题中提出的要求。

我假设您有一个产品型号。确保您的模型中包含以下内容:

class Product < ActiveRecord::Base
  has_many :product_prices

  def latest_price
    product_prices.where("since <= ?",DateTime.now).order(:since).last
  end
end
但要获取最新价格,该方法提供:

@product.latest_price.price # latest price
@product.latest_price.since # when the latest price was active since

注意,我添加了
where("由于抱歉,犯了一个错误,更改了我的答案。问题是,作用域是类的,而不是类实例。例如Product.cheap.this_year,如果定义了适当的作用域:cheap和作用域:this_year,今年将添加所有廉价产品。最新的\u price方法应该用于产品实例。我可能应该注意,如果您使用此选项在大量产品集合中显示价格(例如在索引页中),您将遇到N+1查询问题(可能会更慢)。没有简单的方法解决此问题(因为快速加载无法仅选择最新价格)。因此,如果出现问题,您可能需要缓存最新价格(在product中添加price列,然后在ProductPrice模型中使用after_save回调自动更新产品模型中的价格)我注意到,当我创建新产品时,价格没有保存。我通过添加self.save使其工作。这是一个好主意还是我应该以不同的方式解决此问题?def latest_price=(val)如果不是self.id==nil self.save end pp=ProductPrice.where(:product\u id=>self.id,:since=>DateTime.now.to\u date)。首先创建(:price=>val)pp.price=val pp.save endwith nested attributes,它将需要一些注意。这是可行的,或者您可以尝试使用回调。如果您需要进一步的帮助,请尝试询问新问题
<tbody>
  <% @products.each do |product| %>
  <tr>
        <td><%= product.nameNL %></td>
        <td><%= product.nameFR %></td>
        <td><%= product.descNL %></td>
        <td><%= product.descFR %></td>
        <td><%= product.latest_price.price.to_s %></td>
undefined method `latest_price' for #<Product:0x49e1e48>
  def latest_price=(val)
    pp = ProductPrice.where(:product_id => self.id, :since => DateTime.now.to_date).first_or_create(:price => val)
    pp.price = val
    pp.save
  end
class Product < ActiveRecord::Base
  has_many :product_prices

  def latest_price
    product_prices.where("since <= ?",DateTime.now).order(:since).last
  end
end
@product.find(123)
@product.product_prices.each do |price|
  # each price for the product found here
end
@product.latest_price.price # latest price
@product.latest_price.since # when the latest price was active since
@new_price = ProductPrice.create(:price => ?,
                                 :product_id => @product.id,
                                 :since => DateTime.now)
@new_price = ProductPrice.create(:price => ?, :since => DateTime.now)
@product.product_prices.push(@newprice)
@product.save
@product.product_prices << @newprice # this autosaves