# Can't update one model from another model (polymorphic models)

**URL:** <https://www.ruby-forum.com/t/cant-update-one-model-from-another-model-polymorphic-models/190776>\
**Category:** Rails\
**Created:** [June 27, 2010, 6:24pm UTC](https://www.ruby-forum.com/t/cant-update-one-model-from-another-model-polymorphic-models/190776 "2010-06-27T18:24:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ali](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8c91f0/32.png) [@ali](https://www.ruby-forum.com/u/ali)\
**Post date:** [June 27, 2010, 6:24pm UTC](https://www.ruby-forum.com/t/cant-update-one-model-from-another-model-polymorphic-models/190776/1 "2010-06-27T18:24:15Z")

</div>

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
