如何在Ruby On Rails中用SQL计算年龄?User模型Scope报错求助
User模型Scope筛选年龄范围报错解决方案
问题描述
尝试为User模型创建筛选指定年龄范围的scope,代码如下:
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) }
执行时出现错误:
ERROR: missing FROM-clause entry for table "profile" (PG::UndefinedTable)
已尝试添加SELECT birth_date FROM profile(语法错误)、在查询末尾添加.references(:profiles)(无效),需要解决方法。
解决建议
修正SQL表名拼写:Rails默认将模型名复数化作为数据库表名,
Profile模型对应的表是profiles,所以WHERE条件里要使用复数表名:scope :select_by_age_range, lambda { |age_range| includes(:profile).where("(date_part('year', now()) - date_part('year', profiles.birth_date)) >= ? AND (date_part('year', now()) - date_part('year', profiles.birth_date)) <= ?", age_range.first, age_range.last) }改用Rails查询接口简化逻辑(推荐):避开直接写SQL,通过计算出生日期范围反向筛选年龄,结果更准确(避免生日未过却算满岁的问题):
scope :select_by_age_range, lambda { |age_range| min_age, max_age = age_range min_birth_date = Date.today - max_age.years max_birth_date = Date.today - min_age.years includes(:profile).where(profile: { birth_date: min_birth_date..max_birth_date }) }确认关联关系正确性:检查User模型是否正确定义了与Profile的关联:
# app/models/user.rb class User < ApplicationRecord has_one :profile, dependent: :destroy end同时Profile模型需包含
user_id外键关联:# app/models/profile.rb class Profile < ApplicationRecord belongs_to :user end
内容的提问来源于stack exchange,提问作者Shruikan
相关产品推荐
相关产品推荐

