Re: validates_associated doesn''t actually validate anything

Scott Barron
Thu, 16 Jun 2005 17:10:01 -0000

On Jun 16, 2005, at 11:01 AM, AJ Schuster wrote:

> I am working with three models: Site, Customer, and Contract. Relevant
> portions of classes follow:
>
> class Site < ActiveRecord::Base
>        has_many :contracts
> end
>
> class Customer < ActiveRecord::Base
>        has_many :contracts
> end
>
> class Contract < ActiveRecord::Base
>        belongs_to :customer
>        belongs_to :site
>
>        validates_associated :customer
>        validates_associated :site
> end
>
> When I try to create a contract with invalid customer_id and site_id
> fields, however, no errors are raised. I wind up with rows in my
> contract table that reference nonexistent customer and site rows.
>

validates_associated doesn''t quite work that way.  You need to actually
associate the objects first.  For example, this would fail:

# Modify Site to show an invalidity
class Site < ActiveRecord::Base
   has_many :contracts
   validates_presence_of :name
end

c = Contract.new
s = Site.new
c.site = s
c.save => false because the site is invalid (we gave it no name)

If you need to use the id numbers you''ll probably need to write your
own custom validation code, otherwise you could do something like:

c = Contract.new
c.site = Site.find(params[:site_id])
c.customer = Customer.find(params[:site_id])
c.save

and handle any errors occuring there (e.g. find throwing
RecordNotFound, or using any of the other finders and their errors).

-Scott


_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org