views:

22

answers:

1

I have an item model that has a name and a price (int). How could I make it so that when the user selects the name from a drop down the price will automatically be added to the db?

My name drop down is populated by a hash of this format: THINGS = { 'Item 1' => 'item1', 'Item 2' => 'item2', etc } I'm thinking that a large switch statement where I do something like

case s
    when hammer
        item.price = 15
    when nails
        item.price = 5
    when screwdriver
        item.price = 7
end

But I'm not sure where I would put this switch.

Thanks

+2  A: 

You need push it in a before_save callback.

Inside this callback you check the name choose by your user and update the price

class Item

  before_save :update_price

  def update_price
    self.price = Product.find_by_name(self.name).price
  end
end

You can do in before_validation too if you want validate that your price is really define in your model

class Item

  before_validation :update_price
  validates_presence_of :price

  def update_price
    self.price = Product.find_by_name(self.name).price
  end
end
shingara
This isn't quite what I wanted. I have a hash of items, and I need to associate the items from the hash with prices automatically. So basically, I have `THINGS = { 'A Hammer' => 'hammer', 'Some Nails' => 'nails', etc }`. What I need is a way to make is so that when 'hammer' is selected that a price of say 10 is set.
Reti
Actually, I figured it out. Thanks for the help!
Reti