I have created a model that looks like this:
class Parent < ActiveRecord::Base
attr_accessible :child, :child_id
has_one :child, :class_name => 'Child', :autosave => true, :inverse_of => :parent
#parent's validations
validates_associated :child
end
And the child model is like:
class Child < ActiveRecord::Base
attr_accessible :parent, :parent_id
belongs_to :parent, :inverse_of => :child
validates_presence_of :parent
#Other custom validations...
end
When I am at the new child's page, if the user does not choose a previously created parent for the child, I want to force him to create one at the same time he creates the child. It's working fine if the user fills in all the data correctly for the child and the parent, but if the parent has any validation issue on a given field, the only message I get is: "Parent cannot be blank"
I wanted to show to the user the same message it would show if he was creating the Parent alone. That should be something like: "Field X of Parent is too short".
Is it possible, using validates_associated or with some similar helper?
Thanks in advance!
Answering my own question.. The problem was the line:
validates_associated :child
the :autosave and the :inverse_of options already do what I wanted. The validates_associated is unnecessary and, as I read, deprecated.
The :autosave option makes the parent save the loaded child that is associated, before saving the parent.
With the :inverse_of option, it will save the child, run its validations and, if something's wrong, add the child's errors to the parent without saying that the "child is invalid".
Also..I did not use the accepts_nested_attributes_for. So I loaded the child and the parent at the parent's controller and then saved the parent:
@parent = Parent.new(params[:parent])
@parent.build_child(params[:parent][:child])
if @parent.save
redirect_to(@parent ....etc.....
The errors flashed as I wanted.
Bye :)