价格的活动记录嵌套属性

时间:2012-08-19 22:07:40

标签: ruby-on-rails-3 activerecord

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

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

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

我已经找到了有关嵌套属性的文章,我认为这是可行的方法。谁能告诉我应该怎么做?

编辑:感谢您的回复,我尝试按照您的说法实施,我现在在product.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 我还尝试将last_price添加到attr_accessible

但我总是得到这个错误:

undefined method `latest_price' for #<Product:0x49e1e48>

EDIT2:它现在有效。我还发现如果我添加这个:

  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

然后它完全按照我在问题中要求的那样做。

1 个答案:

答案 0 :(得分:0)

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

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