Reputation: 355
Im trying to create a scope on a Model at my project, but I want that the query filter the elements basead on a method at my Model.
This is my model:
class Talent < ApplicationRecord
scope :public_profile, -> { Talent.all.select{ |t| t.age > 13 } }
def age
now = Time.now.utc.to_date
now.year - self.birth_date.year - ((now.month > self.birth_date.month ||
(now.month == self.birth_date.month && now.day >= self.birth_date.day)) ? 0 : 1)
end
When I try to run this scope I get the error:
NoMethodError: undefined method `year' for nil:NilClass
from app/models/talent.rb:195:in `age'
from (irb):6:in `block in irb_binding'
from (irb):6
The line 195 its on my method age. So, probably when doing the select, my element is coming nil.
What Im doing wrong here?
Upvotes: 0
Views: 30
Reputation: 20263
Given:
NoMethodError: undefined method `year' for nil:NilClass
And given that you're only calling the method year
twice in the age
method:
def age
now = Time.now.utc.to_date
now.year - self.birth_date.year - ((now.month > self.birth_date.month ||
(now.month == self.birth_date.month && now.day >= self.birth_date.day)) ? 0 : 1)
end
And given that now
is certain not to be nil
:
now = Time.now.utc.to_date
It would seem that self.birth_date
is returning nil
. And, as the error states, nil
doesn't have the year
method.
Upvotes: 2