6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Keisuke Death MarchAdvent Calendar 2023

Day 23

Rails7系から追加された便利そうなメソッド

Last updated at Posted at 2023-12-23

はじめに

Railsの7系を触っていてあまり見慣れないメソッドに出会う機会が多いので、改めてまとめてみました。

sole

# Userモデルに対して、usernameが特定の値であるレコードを取得しようとする。
# usernameがユニークであることが期待されている場合に使用する。

begin
  user = User.where(username: 'unique_username').sole
  puts user.name
rescue ActiveRecord::RecordNotFound
  # レコードが見つからなかった場合の処理
  puts 'ユーザーが見つかりませんでした。'
rescue ActiveRecord::SoleRecordExceeded
  # 複数のレコードが見つかった場合の処理
  puts '期待されるユーザーが複数存在します。'
end

excluding

post_one = Post.find(1)
post_two = Post.find(2)

Post.all.excluding(post_one, post_two)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" NOT IN (1, 2)

in_order_of

User.in_order_of(:id, [1, 5, 3])
# SELECT "users".* FROM "users" ORDER BY FIELD("users"."id", 1, 5, 3)

destroy_by

Person.destroy_by(id: 13)
Person.destroy_by(name: 'Spartacus', rating: 4)
Person.destroy_by("published_at < ?", 2.weeks.ago)

delete_by

Person.delete_by(id: 13)
Person.delete_by(name: 'Spartacus', rating: 4)
Person.delete_by("published_at < ?", 2.weeks.ago)

touch_all

# 現在時刻に設定
Person.all.touch_all
# "UPDATE \"people\" SET \"updated_at\" = '2018-01-04 22:55:23.132670'"
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?