[Rails] validation and update

Peter Michaux
Mon, 13 Mar 2006 06:54:46 -0000

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