首页 文章

Rails嵌套模型更新不使用子控制器 . 叫什么?

提问于
浏览
0

我有食谱模型和成分模型 . 成分belongs_to食谱和食谱has_many成分 . 一切都很好 . 嵌套属性正在更新 .

但我在嵌套模型上有一个属性,我想在它存储到数据库之前进行操作 . 我在IngredientsController更新方法中有代码来处理这个问题 .

我期待RecipeController的更新方法在更新嵌套的Ingredients时调用IngredientController的更新方法 . 这显然不会发生 .

在更新过程中,我可以使用什么机制来操作嵌套模型对象?

更多细节:我将成分数量存储在数据库中作为浮点数(1.25,0.33333,3.5,4.0等) . 我希望用户能够以邋fraction的分数(1 1 / 4,1 / 3,3 / 4,4)来查看和编辑该值 .

所以我编写了String.to_f_sloppy和Float.to_s_sloppy函数来操作数字 . 显示,没有问题,我只使用ingredient.quantity.to_s_floppy . 但是当有人编辑该成分并更改数量时,当它到达before_update和before_validation函数时,该值已经更改(就像它通过to_f运行) .

以下是通过的参数:参数:{“utf8”=>“√”,“authenticity_token”=>“ojOwp68P3ObiufowfKtbfYxpV31vZPz64qYQAL / 1ld8Px93OrDX2Gvy / yxljENJOhiLW3DUoE0C2upvHuF3CA ==”,“recipe”=> {“user_id”=>“1” ,“name”=>“Chicken Piccata”,“description”=>“”,“category”=>“entree”,“yield”=>“4.0”,“ingredients_attributes”=> {“0”=> {“ recipe_id“=>”12“,”name“=>”去皮无骨鸡胸肉“,”unit_id“=>”40“,”数量“=>”2 1/2“,”评论“=>”“, “_destroy”=>“0”,“id”=>“122”}}},“commit”=>“保存食谱”,“id”=>“12”}

在ingredients.rb中,我有:

class Ingredient < ActiveRecord::Base
  belongs_to :unit
  belongs_to :recipe
  before_update :translate_quantity

  def translate_quantity
    puts "UPDATE QUANTITY IS #{self.quantity}"
  end
end

输出:UPDATE QUANTITY IS 2.0

所以在我获得 Value 之前,它已被改变 .

2 回答

  • 0

    您可以使用Activerecord的回调,这些回调在模型上实现,它允许您使用它们修改记录 .

    你想要的是 before_update 回调 .

    更多信息here .

    像这样的东西 .

    class Ingredient < ActiveRecord::Base
      ...
      before_update :stuff
    
      private
        def stuff
          # do stuff
        end
    end
    
  • 0

    我找到了解决方案 . 我用这个答案:

    How can I override the attribute assignment in an active record object?

    要覆盖模型中的行为:

    def quantity=(value)
        super(value.to_f_sloppy)
    end
    

相关问题