On Feb 4, 2011, at 3:30 PM, Paul wrote:

> Rails is great and most things just work easily. However, I've never
> been able to get a definite answer on whether one should do,
> 
> validates :parent, :presence => true
> 
> or,
> 
> validates :parent_id, :presence => true
> 
> given,
> 
> class Parent
> end
> 
> class Child
>  belongs_to :parent
> end
> 
> I've always thought that validating the :parent (and not the foreign
> key) is the *more* correct thing to do ... but I don't understand why
> Rails does not reset the parent association when the parent_id is
> changed as demonstrated here,
> 
> child = Child.find(..)
> child.parent_id = nil
> puts child.valid? # outputs false
> 
> child = Child.find(..)
> child.parent
> child.parent_id = nil
> puts child.valid? # outputs true!
> 
> Any thoughts?
> 

This is due to the way that association proxies lazy load their targets. In the 
first case, if you only loaded the child record, and modified the parent_id 
attribute, then you never load the parent object, because you never accessed 
the association proxy.

In the latter case, you did access the association proxy, so the parent got 
loaded, but then you modified the parent_id, directly. I'd recommend that you 
be consistent -- if you're checking if the associated object exists, set the 
association to nil, instead of the id, and you shouldn't have a problem.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to