strapyourself.in and flouri.sh

Why associated models don't save

May 21st, 2007

Acts_as_taggable conflicting with has_one

In our dashboard app, we attempted to use the following in a controller:

def create
  @employee = Employee.new(params[:employee])
  @employee.address = Address.new(params[:address])
  @employee.save
end

class Employee < ActiveRecord::Base
  has_one :address, :as => :addressable
  acts_as_taggable
end

Result: tags in params[:employee][:tag_list] weren't being saved correctly. I then changed the order in the model:

class Employee < ActiveRecord::Base
  acts_as_taggable
  has_one :address, :as => :addressable
end

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.

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
  
  validates_presence_of :street, :city, :state, :postal, :country

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.

class Employee < ActiveRecord::Base
  has_one :address, :as => :addressable
  validates_associated :address
  acts_as_taggable
end

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!

Originally posted on ELC

Sorry, comments are closed for this article.

original design by gorotron ported by railsgrunt powered by mephisto