On 5/02/2011, at 9:30 AM, Paul <[email protected]> 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 >
Validate the object, not the foreign key. Otherwise a record with parent_id of -99, 0 or some other nonsense will still pass. > 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, As Jon mentioned there is some code for this kind of thing in master. As for the historical reason it did that, it's trickier than it looks :) There can be multiple (or zero) associations for a given _id column, and a patch we tried a while back didn't handle all those potential cases. There's no deep philosophical reason it works that way, it's just historical / evolutionary artifacts sneaking up on you. > > 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? > > -- > 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. > -- 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.
