ruby-on-rails - 如何根据日期作为数据库中的列的确切年份过滤用户?

标签 ruby-on-rails ruby

我想在我的模型上使用 SQL 命令过滤用户,例如,如果用户刚好 5 岁。我怎样才能做到这一点?范围查询有效,但删除范围不会返回任何内容。

这行得通,但我希望它准确输出 21 岁的年龄(如果生日是 1997/01/01)并且不应包括 22 岁。

users = users.where(["birthdate >= ? AND birthdate <= ?", 22.years.ago + 1.day, 21.years.ago])

我试过这个但它没有输出任何东西:users = users.where(["birthdate = ?", 21.years.ago])

用户架构

create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.string "position"
t.string "employee_id"
t.string "first_name"
t.string "middle_name"
t.string "last_name"
t.string "gender"
t.string "address"
t.string "sss_number"
t.string "tin_number"
t.string "phil_health"
t.string "emergency_name"
t.string "emergency_contact"
t.date "birthdate"
t.date "date_hired"
t.string "role", default: "user"
t.integer "department_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

结束

最佳答案

您可以使用 Range 和方法 beginning_of_yearend_of_year,如下所示:

date = 22.years.ago #example
User.where(birthdate: date.beginning_of_year..date.end_of_year)

关于ruby-on-rails - 如何根据日期作为数据库中的列的确切年份过滤用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50253457/

相关文章:

ruby-on-rails - Windows/Ruby/Rails 安装 --- .cannot load such file -- sqlite3/sqlite3_native windows

ruby-on-rails - Cloud9 警告我可以忽略吗?

ruby-on-rails - 路由错误 没有路由匹配 [POST] "/movies/9/edit"

ruby-on-rails - 如何向所有属性为 true 的用户发送电子邮件 (Rails Mailer)

javascript - rails : has_many association through array of object IDs from form

ruby-on-rails - 根据格式路由到不同的操作

mysql - ActiveRecord 连接和位置

ruby-on-rails - 带有 FactoryGirl 序列的自定义范围

ruby-on-rails - Ruby/Rails 小数点百分比

ruby - redis 键没有过期