I have a rails model that looks something like this:
class Recipe < ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join('\n') end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split('\n').each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end
The idea is that when I create the ingredient from the webpage, I pass in the ingredients_string and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the ingredient_string is defined in the set_ingredients method?
Using these two together are probably causing your issues. Both are trying to define an
ingredients_stringmethod that do different thingsGet rid of the
attr_accessor, thebefore_save,set_ingredientsmethod and define your owningredients_string=method, something like this:Note I just borrowed your implementation of
set_ingredients. There’s probably a more elegant way to break up that string and create/delete Ingredient model associations as needed, but it’s late and I can’t think of it right now. 🙂