Validation and update

Hi,

I have validation working in a situation similar to the following.
(Please forgive any minor typos below)

class Department < ActiveRecord::Base
has_many :people
end

class Person < ActiveRecord::Base
belongs_to :department
validates_presence_of :name
end

@department = Department.new(:name=>“bedrock”)
@department.people << Person.new(:name=>“fred”)
@department.people << Person.new
if @department.save

redirect

else

validation failed

This is what actually happens in this example since one person

doesn’t have a name
end

However if I update a person in the department with bad data and save,
no errors are created and only the new department information is saved

setup

@department = Department.new(:name=>“bedrock”)
@department.people << Person.new(:name=>“fred”)
@department.save

try to update with some bad data

@department = Department.find_by_name(“bedrock”)
@department.name = “BEDROCK”
@department.people[0].name = “”
if @department.save

This is what actually happens in this example eventhough there

should now be a name error.

The new capitalized department name is stored in the database

redirect

else

validation failed

end

How can I get ActiveRecord to validate all the way into the person
objects when updating? I tried the valid? method and that didn’t work
either. It only checks the Department object.

Thanks,
Peter

Hi,

I’ve been trying to figure this out but no luck.

I looked in the activerecord source at the save, create and update
functions. In the case of create, I don’t see how activerecord knows
to implicitly run a transaction with the parent and child tables. I
don’t see any calls down to the child models. I’m glad that
activerecord does this but I was hoping to see hwere update differs
from create.

Any ideas?

Peter

What about *validates_associated?

*If that doesn’t work, maybe your controller logic can perform a
“valild?”
call on your Person object…?

On 3/13/06, Michael G. [email protected] wrote:

What about validates_associated?

Thanks Michael.

I guess I will have to build some controller logic to make sure that
if the department and associated people all validate then the save
happens as a transaction. I thought that the rails save would do this
for me but it doesn’t seem to when using it to update records.
Strange. If anyone else knows why save doesn’t I’m interested.

Thanks,
Peter