0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Exactly. So, the scope of self doesnt work when called from a scope? Should I create a method with a paramether and pass the object to the method?
@FernandoMaymone this has nothing to do with the scope of self this has to do with the fact that one of your records does not have a birth_date. That being said select will return an Array and a scope should always return an ActiveRecord::Relation so that is going to cause an issue
Exactly. The problem was the birth_date comming nil. Thanks guys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.