The ELC Community Blog
A knowledge exchange on Ruby on Rails and Agile Development
Why associated models don't save
by stevend on May 22, 2007
Acts_as_taggable conflicting with has_one
In our dashboard app, we attempted to use the following in a controller:
1 <pre>def create
2 @employee = Employee.new(params[:employee])
3 @employee.address = Address.new(params[:address])
4 @employee.save
5 end
6
7 class Employee < ActiveRecord::Base
8 has_one :address, :as => :addressable
9 acts_as_taggable
10 end</pre>
Result: tags in params[:employee][:tag_list] weren't being saved correctly. I then changed the order in the model:
1 <pre>class Employee < ActiveRecord::Base
2 acts_as_taggable
3 has_one :address, :as => :addressable
4 end</pre>
The tag_list gets saved! What gives?
Failed validation weirdness
The culprit in this case was validation. There are two after_save filters involved: acts_as_taggable and has_one. Acts_as_taggable always returns true, continuing the the filter chain, regardless of the success of tagging/tag updating (I this that's a bug actually). Not the case for has_one, however, where the rails system checks that the associated model saves before continuing the filter chain. In our test, we were not passing in enough params[:address] to make the Address.new save correctly.
1 <pre>
2 class Address < ActiveRecord::Base
3 belongs_to :addressable, :polymorphic => true
4
5 validates_presence_of :street, :city, :state, :postal, :country
6 </pre>
This situation was our own fault, but nonetheless not trivial to debug. Rails did not help us understand what went wrong, just that no SQL to save the tags was ever getting run.
1 <pre>class Employee < ActiveRecord::Base
2 has_one :address, :as => :addressable
3 validates_associated :address
4 acts_as_taggable
5 end</pre>
Moral of the story: always use validates_associated for has_one and has_many associations because they will not stop the main model from being saved if they fail validation!
Timeline
- Conditional Action Caching with Cache_Fu
- SSH Configuring RightScale's RightImage FC6V2
- Preloading fixtures
- Using and testing multiple databases in rails part 2
- RailsConf Europe
- Why associated models don't save
- RailsConf 2007 Highlights
- RailsConf 2007 - Day 1
- Don't mix attr_protected and attr_accessible.
- sortable column headers
- DRY validates_inclusion_of with introspection
Comments
hr7fy6i6pa816w0o