价格的活动记录嵌套属性



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

我有两个型号的产品和产品价格在轨道。

这就是产品价格的样子:

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 ProductPrice < ActiveRecord::Base
  belongs_to :product
  attr_accessible :current, :price, :product_id, :since
end

现在我希望价格可以通过产品访问。它应该始终显示当前价格(只能有一个当前价格/产品。用户还应该能够通过产品编辑价格。如果价格在产品更新中发生了变化,则应插入一个新的ProductPrice,其中current=true,since=current日期。旧的ProductPrices不应再是最新的。

我已经找到了关于嵌套属性的文章,我认为这将是一条路。有人能告诉我该怎么做吗?

编辑:谢谢你的回复,我试着按照你说的实现,我现在在产品中有这个.rb:

class Product < ActiveRecord::Base
  belongs_to :menu_category
  belongs_to :menu
  has_many :product_prices, :dependent => :delete_all
  scope :latest_price, lambda {product_prices.where("since <= ?",DateTime.now).order(:since).last}
  attr_accessible :active, :descFR, :descNL, :image, :menu_category_id, :menu_id, :nameFR, :nameNL
  mount_uploader :image, ImageUploader    
end

在我的产品索引页面中,我有:

<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>

我还试过:product.latest_price.price或product.latest_price我还尝试将最晚的价格添加到attr_accessible 中

但我总是遇到这样的错误:

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

注意,我添加了where("since <= ?",DateTime.now)。这可以让你提前安排价格(如果是在未来)。

为产品添加新价格:

@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