开发者

Ruby on Rails: Set data in my model based on another field

开发者 https://www.devze.com 2023-01-11 11:05 出处:网络
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?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号