Reputation: 3555
I have a question about the ActiveRecord's validates
For example, with this code:
class Person < ApplicationRecord
validates :name, presence: true
def name
'hello world'
end
end
There is a getter method name
to return a string as the name. There is also a column in the database table, whose name is name
.
I understand that, when we call person.name
, the method (not the db record) is used. However, for the validates
, do we use the method's return value or the db records to check?
I tried to read the ActiveRecord source code, but quickly got lost :-( Any help or pointer is much appreciated!
Upvotes: 1
Views: 51
Reputation: 10564
It uses the getter method. It's straight-forward to test:
class Person < ApplicationRecord
validates :name, presence: true
def name
binding.irb
end
end
Then in the Rails console:
irb(main):002:0> Person.create!
From: /Users/foo/app/models/person.rb @ line 5 :
3:
4: def name
=> 5: binding.irb
6: end
7:
And if you simply exit
from there (implying nil
) you'll receive:
Validation failed: Name can't be blank (ActiveRecord::RecordInvalid)
Upvotes: 1