Re: validates_associated & foreign keys

Birgit Arkesteijn
Tue, 01 Jul 2008 13:27:13 -0000

Hi Frederick,

Thanks for your message.
I changed my ''belongs_to'' and ''has_many'' and
(indeed) the problem persists.

I know that RoR doesn''t really know about foreign keys, but what is the
purpose of validates_associated ??
http://ar.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M000090

What kind of associating does it perform, it not on the values between
two models?

Maybe I should rephrase my question ...

If validates_associated doesn''t do the trick, how do I write a
validation that checks that area_codes_market.area_code_id == area_codes.id

Thanks, Birgit


On 01/07/08 13:47, Frederick Cheung wrote:
>
>
> 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
> >

--
-- Birgit Arkesteijn, birgit-YRFHH29wTjy9FHfhHBbuYA@public.gmane.org,
-- Westhawk Ltd, Albion Wharf, 19 Albion Street, Manchester M1 5LN, UK
-- Company no: 1769350
-- Registered Office:
-- 15 London Road, Stockton Heath, Warrington WA4 6SJ. UK.
-- tel.: +44 (0)161 237 0660
-- <URL: http://www.westhawk.co.uk>