[Rails] 연령별로 검색
하고 싶은 일
생일을 저장하는 데 사용되는 Date형 birthday 열을 가진 User 모델이 있습니다.나이부터 나이까지의 User를 검색하고 싶습니다.
메서드
설치 예
다음 User 모델은 User입니다.by_age로 실시되고 있습니다.class User < ApplicationRecord
# ある年齢 from からある年齢 to までの User を検索する。
scope by_age, (lambda do |from: 0, to: 999, today: Date.today|
# 今日のちょうど to 年前の日付の 1 日後から
date_from = today.ago((to + 1).years).since(1.day)
# 今日のちょうど from 年前までを検索する。
date_to = today.ago(from.years)
where(birthday: date_from..date_to)
end)
# 年齢を (簡易的に) 計算する。
# TODO: うるう日やうるう秒を考慮する。
def age(today = Date.today)
((today.to_time - birthday.to_time) / 1.year.seconds).floor
end
def formatted_birthday
date = birthday.strftime('%Y/%m/%d')
wday = %w[日 月 火 水 木 金 土][birthday.wday]
"#{date} (#{wday})"
end
end
실행 예
# (あえて境界値がうるう日前後になるように)
# 今日の日付が 2020/02/29 (土) だと仮定する。
today = Date.parse('2020/02/29')
User.order(:birthday).each do |user|
puts("#{user.formatted_birthday} #{user.age(today)} 歳 #{user.name}")
end
# 1989/02/28 (火) 31 歳 ピカチュウ
# 1989/03/01 (水) 30 歳 カイリュー
# 2000/02/29 (火) 20 歳 ヤドラン
# 2000/03/01 (水) 19 歳 ピジョン
# 20 〜 30 歳の User を検索する。
User.by_age(from: 20, to: 30, today: today).pluck(:name)
#=> ["カイリュー", "ヤドラン"]
Reference
이 문제에 관하여([Rails] 연령별로 검색), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/QUANON/items/0e4e32e92ca8a5238888
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
설치 예
다음 User 모델은 User입니다.by_age로 실시되고 있습니다.
class User < ApplicationRecord
# ある年齢 from からある年齢 to までの User を検索する。
scope by_age, (lambda do |from: 0, to: 999, today: Date.today|
# 今日のちょうど to 年前の日付の 1 日後から
date_from = today.ago((to + 1).years).since(1.day)
# 今日のちょうど from 年前までを検索する。
date_to = today.ago(from.years)
where(birthday: date_from..date_to)
end)
# 年齢を (簡易的に) 計算する。
# TODO: うるう日やうるう秒を考慮する。
def age(today = Date.today)
((today.to_time - birthday.to_time) / 1.year.seconds).floor
end
def formatted_birthday
date = birthday.strftime('%Y/%m/%d')
wday = %w[日 月 火 水 木 金 土][birthday.wday]
"#{date} (#{wday})"
end
end
실행 예
# (あえて境界値がうるう日前後になるように)
# 今日の日付が 2020/02/29 (土) だと仮定する。
today = Date.parse('2020/02/29')
User.order(:birthday).each do |user|
puts("#{user.formatted_birthday} #{user.age(today)} 歳 #{user.name}")
end
# 1989/02/28 (火) 31 歳 ピカチュウ
# 1989/03/01 (水) 30 歳 カイリュー
# 2000/02/29 (火) 20 歳 ヤドラン
# 2000/03/01 (水) 19 歳 ピジョン
# 20 〜 30 歳の User を検索する。
User.by_age(from: 20, to: 30, today: today).pluck(:name)
#=> ["カイリュー", "ヤドラン"]
Reference
이 문제에 관하여([Rails] 연령별로 검색), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/QUANON/items/0e4e32e92ca8a5238888텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)