Don't validate belongs_to, or else...
Over on rails-core, I posted Edge Rails fails saving parent when has_many child ?.
The models I am using are:
As is, it was impossible to use the normal build and save idiom:
Well, of course. I know invoice can’t be blank. If I remove :invoice from the validates_presence_of, things work out fine:
Digging into the code, ActiveRecord::Associations::AssociationProxy#set_belongs_to_association_for it turns out that only the foreign key is assigned to the child instance, not the full parent model. The behavior as seen above is therefore “normal”.
Turns out that if I validate the foreign key instead, things work perfectly:
Lesson learned: don’t validate the presence of the associated model, only it’s foreign key.
October 12th, 2007 at 10:25 PM
I’ve noticed that rails is a little inconsistent here, in some places you reference the associated model by name, and in other places you reference it by its foreign key.
Rails doesn’t support this yet, but I believe the only place in the entire model where you should type the name of the foreign key is when defining the associated model, like in belongs_to… and only when you’re breaking away from the naming convention for its name.
Everywhere else you should just be able to reference the name of the associated model and it should do the right thing.
For example when you use stuff like validates_uniqueness_of, the :scope could be :associated_model, rather than only :associated_model_id.