Re: validates_associated & foreign keys

Birgit Arkesteijn
Wed, 02 Jul 2008 09:27:26 -0000

Thanks Wolas and Fred for you help and explanation.

I''ve decided to change the UI of market, so it will display checkboxes
for the available area_codes. This way I avoid having the check for
foreign keys, since the UI will only offer what''s available.

For newbies (such as myself, specially when using Rails 2.0 and getting
very confused when looking at Rails 1.X examples), the following really
helped me out:

PaulBarry.com - has_many :through checkboxes
http://paulbarry.com/articles/2007/10/24/has_many-through-checkboxes

Cheers, Birgit


On 01/07/08 14:50, "Wolas!" wrote:
> The purpose of validates_associated is to know whether an object
> associated with another object is valid (as in returns true when
> calling the valid? method) This allows you, for example to check
> whether an area code object associated to a market is valid before you
> save both. if the associated object fails validation, then the parent
> object cannot be saved either.
>
> What Frederick is talking about (dangling references) is a check that
> rails will not do for you on write (as in creating a row in the db)
> but on read. Specifically on method calls to other objects.
>
> So for instance i can create Product.new(:category_id => 2) where
> product belongs to category. I save it no trouble, even change the
> category_id later on
>
> @product.category_id = 999
> => 999
> @product.save
> => true
>
> but then:
>
> @product.category
> => nil                     # if Category.find_by_id(999) is nil
>
> @product.category_id
> => 999
> dunno if this helps, just thought it could shine some light for people
> with similar problems
>


--
-- 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>