In custom validation methods, why are the attributes passed as local variables instead of being accessible as instance variables?
I was expecting to use @title instead of title in the custom validation below, but @title is nil in the code below. title contains the actual data.
attr_accessible :title
validate :do_check_title
def do_check_title
title =~ /^Alice in/ || errors.add(:title, "Not Alice in Wonderland")
end
Looking through the active_record/core.rb
def initialize(attributes = nil)
...
assign_attributes(attributes) if attributes
...
end
And then in active_record/attribute_assignment.rb
def _assign_attribute(k, v)
public_send("#{k}=", v)
So I guess, the attributes should be available as instance variables in the validation function.
Why are they nil?
It doesn’t really matter if you access these from a validation or other instance methods. You can see what’s happening from the console (pry):
This gives you something like this:
Now if you take a look at the
write_attributemethod, you can see that it deletes attribute cache etc. and then assign toattributesand it’s just a hash.So from now on, instead of the boring
u.first_name = "foo", you can use this:and it will do the same thing (3.2.10).