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 sc开发者_StackOverflowrewdriver
item.price = 7
end
But I'm not sure where I would put this switch.
Thanks
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
加载中,请稍侯......
精彩评论