Home > Mobile >  How to calculate age from birth date using SQL in Ruby On Rails
How to calculate age from birth date using SQL in Ruby On Rails

Time:12-28

So I'm trying to create scope for User model. It goes like this:

scope :select_by_age_range, lambda { |age_range|
                                includes(:profile).where("(date_part('year', now()) - date_part('year', profile.birth_date)) >= ? AND (date_part('year', now()) - date_part('year', profile.birth_date)) <= ?", age_range.first, age_range.last)
                              }

I want to select all users in given age_range, but it gives me an error:

ERROR: missing FROM-clause entry for table "profile" (PG::UndefinedTable)

I tried to add SELECT birth_date FROM profile, but it gives me syntax error.

I also tried to add .references(:profiles) at the end of query, but it doesn't help either.

Any suggestions?

Ps. I am not familiar with SQL. What you see here is: "I have no idea what I'm doing"

CodePudding user response:

The table is likely named profiles in the database. Therefore, you have to use profiles.birth_date in the query instead of profile.birth_date.

Btw. I would simplify the query to:

scope :select_by_age_range, lambda { |age_range|
  includes(:profile)
    .where(profiles: { birth_date: (age_range.begin.years.ago..age_range.end.years.ago) })
}
  • Related