I have a Recipes model and an Ingredients model. Ingredients belongs_to Recipes and Recipes has_many Ingredients. Everything is working fine. Nested attributes are being updated.
But I have one attribute on my nested model that I want to manipulate before it gets stored in the DB. I have the code in the IngredientsController update method to handle this.
I was expecting that the RecipeController's update method would call the IngredientController's update method when updating the nested Ingredients. This obviously doesn't happen.
What mechanism can I use to manipulate the nested model objects during the update process?
MORE DETAIL: I'm storing the ingredient quantity in the database as a float (1.25, 0.33333, 3.5, 4.0, etc ). I want the user to be able to see and edit the value as a sloppy fraction (1 1/4, 1/3, 3 1/2, 4 ).
So I wrote String.to_f_sloppy and Float.to_s_sloppy functions to manipulate the numbers. On display, there is no problem, I just use ingredient.quantity.to_s_floppy. But when someone edits the ingredient and changes the quantity, the value is already changed (like it was run through to_f) when it gets to the before_update and before_validation functions.
Here are the parameters that come through: Parameters: {"utf8"=>"√", "authenticity_token"=>"ojOwp68P3ObiufowfKtbfYxpV31+vZPz64qYQAL/1ld8Px93OrDX2Gvy/yxljENJOhiLW3DUoE0C2upvHuF3CA==", "recipe"=>{"user_id"=>"1", "name"=>"Chicken Piccata", "description"=>"", "category"=>"entree", "yield"=>"4.0", "ingredients_attributes"=>{"0"=>{"recipe_id"=>"12", "name"=>" skinless and boneless chicken breasts", "unit_id"=>"40", "quantity"=>"2 1/2", "comment"=>"", "_destroy"=>"0", "id"=>"122"}}}, "commit"=>"Save Recipe", "id"=>"12"}
In ingredients.rb, I have:
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
This outputs: UPDATE QUANTITY IS 2.0
So before I can get to the value, it has been changed.