I’m a completely new rails developer so bear with me 🙂
I have two models named Product and ProductPrice in rails.
This is how ProductPrices looks:
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
And this is how the model looks:
class ProductPrice < ActiveRecord::Base
belongs_to :product
attr_accessible :current, :price, :product_id, :since
end
Now I want the price to be accesible through the Product. It should always show the current price (there can be only one current price/product. The user should also be able to edit the price through product. If the price has changed in an update of the Product then a new ProductPrice should be inserted with current = true and since = the current date. The old ProductPrice should no longer be current.
I already found articles about Nested Attributes and I think that would be the way to go. Can anyone tell me how I should go about to do this?
EDIT: Thanks for the reply, I tried implementing as you said, I have this now in 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
And in my index page of products I have:
<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>
I also tried: product.latest_price.price or product.latest_price
I also tried addint the latest_price to attr_accessible
But I always get this error:
undefined method `latest_price' for #<Product:0x49e1e48>
EDIT2: It now works. I also found out that If I add this:
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
Then it completely does what I asked for in the question.
I assume you have a Product model. Make sure you have the following in your model:
Now you can access all prices with:
But to access the latest price, the method gives you:
Notice I added the
where("since <= ?",DateTime.now). That lets you schedule prices in advance (if since is in the future).To add a new price to the product:
Another way to add a price to the product:
Or: