Re: validates_associated & foreign keys

Frederick Cheung
Tue, 01 Jul 2008 12:47:07 -0000

On Jul 1, 1:06 pm, "Birgit (Westhawk)"
<bir...-YRFHH29wTjy9FHfhHBbuYA@public.gmane.org>
wrote:
> When I create a new area_codes_market record and (deliberately) enter
> an area_code_id or a market_id that is incorrect, Ruby on Rails
> doesn''t flag the error.
> Instead I get an activerecord error on my foreign key constraint.
>
I think you''ve just set your hopes a little too high - rails
doesn''t
really do anything with foreign keys.
All validates_associated does is run the validations on the associated
models. If you were about to create a record with a dangling reference
then there''s just nothing for validates_associated to validate.

On top of that i think you''ve got your associations wired up the wrong
way round. Given that you''ve got area_code_id and market_id columns
(and going by the name of your table) you should have
belongs_to :area_code and belongs_to :market not the has_manys you''ve
currently got (has_many area_codes implies that area_codes has a
area_codes_market_id column)

Fred

> ActiveRecord::ActiveRecordError: Cannot add or update a child row: a
> foreign key constraint fails
> (`TestDoneRight_test`.`area_codes_markets`, CONSTRAINT
> `area_codes_markets_ibfk_2` FOREIGN KEY (`area_code_id`) REFERENCES
> `area_codes` (`id`)): INSERT INTO `area_codes_markets`
> (`area_code_id`, `market_id`) VALUES(2, 1)
>
> Reading the forums and the documentation, I think I have the correct
> naming convention and model.
>
> I found the following onlinehttp://dev.rubyonrails.org/ticket/5369
> However, the patch is for an older ActiveRecord version, so I''ve
got
> no idea how to apply it (assuming it would even work).
>
> Does anyone have a clue how I could fix this?
>
> Thanks, Birgit
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com