Hi. I'm having a little trouble updating a model of mine. So I have a Dimension model which is polymorphic. The 2 derived classes are Fact and Opinion. In my Dimension model I have an after_save callback function that creates an Opinion record whenever a Fact record is created. So it looks like this:
In my fact controller, in the update action, I set the old_name to whatever the fact's name was before its creation. So if the
def create_opinion_if_fact if valuable_type == 'Fact' op = Opinion.find_by_name @old_name
unless op op = Opinion.new op.dimension = Dimension.new :name => name end
op.dimension.name = name op.dimension.desc = desc
# Give the opinions the same associations as the fact op.dimension.concepts.clear
concepts.each do |c| op.dimension.concepts << c end
op.save! end end
In my facts_controller's update and create actions, I set Dimension.old_name to Fact.find(params[:id]).dimension.name. Since this will have the old name in it. Of course when creating a new fact, this will be empty, so in that case (the create action) I set old_name to params[:fact][:dimension_attributes][:name].
So when I create a new fact, the opinion gets created as well. When I try and update a fact, I get a validation error saying that the 'name' is already taken. But I don't understand why this happens because if I update a fact and don't change a name, then the first line in my create_opinion_if_fact function will find a fact that's already there, and then the save! should just update it.
Also, I have "validates_uniqueness_of :name, :scope => :valuable_type, :case_sensitive => false" in my Dimension model. Valuable is the polymorphic link in this case.
One other thing. When I get rid of op.save! at the end of that function and replace it with op.save false, I get 2 opinions created for every fact. When I change it to just op.save, then everything works fine (because it doesn't throw an exception and fails silently instead).
Thanks for any help