2010-08-12 87 views
2

我有一个item模型,它具有nameprice(int)。我怎么能这样做,以便当用户从下拉菜单中选择name价格将自动添加到数据库?Ruby on Rails:基于另一个字段在我的模型中设置数据

name下拉本格式的哈希值填充:THINGS = { 'Item 1' => 'item1', 'Item 2' => 'item2', etc }我在想,在我这样做

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

大switch语句,但我不知道,我会把这个开关。

谢谢

回答

2

您需要在before_save回调中推送它。

这里面回调您检查名称由用户选择和更新价格

class Item 

    before_save :update_price 

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

可以在before_validation做太多,如果你想验证你的价格是真的在你的模型中定义

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

这不是我想要的。我有一些项目的散列,我需要自动将散列中的项目与价格关联起来。所以基本上,我有'THINGS = {'锤子'=>'锤子','一些钉子'=>'指甲'等''。我需要的是这样一种方式,即当选择“锤子”时,设置10的价格。 – Reti 2010-08-12 08:31:57

+0

其实,我明白了。谢谢您的帮助! – Reti 2010-08-12 08:33:24

相关问题