Hey, In edge rails there is a mechanism for checking whether the loaded association target is "stale" - so if you do record.foo_id = x, then record.foo will load the target afresh.
I'm not sure whether it necessarily works with validation like this, but hopefully it does. [I haven't tried.] Just to emphasise, this is new in edge - it is not in the 3-0-stable branch. Jon On Fri, 2011-02-04 at 15:39 -0500, Ernie Miller wrote: > 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. > -- http://jonathanleighton.com/
signature.asc
Description: This is a digitally signed message part
