【问题标题】:Ruby on Rails: Set data in my model based on another fieldRuby on Rails:根据另一个字段在我的模型中设置数据
【发布时间】:2010-08-12 16:10:57
【问题描述】:

我有一个 item 模型,它有一个 name 和一个 price (int)。我怎样才能使当用户从下拉列表中选择name 时,价格会自动添加到数据库中?

我的name 下拉列表由这种格式的哈希填充:THINGS = { 'Item 1' => 'item1', 'Item 2' => 'item2', etc } 我在想一个大型 switch 语句,我在其中执行类似的操作

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

但我不确定我应该把这个开关放在哪里。

谢谢

【问题讨论】:

    标签: ruby-on-rails autocomplete


    【解决方案1】:

    您需要在 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
    

    【讨论】:

    • 这不是我想要的。我有一个项目哈希,我需要自动将哈希中的项目与价格相关联。所以基本上,我有THINGS = { 'A Hammer' => 'hammer', 'Some Nails' => 'nails', etc }。我需要的是一种制作方法,以便在选择“锤子”时设置 10 的价格。
    • 其实我想通了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2022-07-20
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多