LoginSignup
0
0

More than 1 year has passed since last update.

Active Record attribute methodまとめ(その④: Query, Read, Write編)

Last updated at Posted at 2022-09-12

はじめに

今回はActive Recordのattribute methodのうち、Query, Read, Writeメソッドをまとめていきます。
(2022年6月時点。Rails7.0対応。)
その他のメソッドについては、別記事でまとめてますので是非ご覧ください。
ActiveRecord attribute methodまとめ(その①: BeforeTypeCast編)
ActiveRecord attribute methodまとめ(その②: Dirty編)
Active Record attribute methodまとめ(その③: PrimaryKey編)

検証環境

以下のschemaとmodelに基づいて検証を行なっています。

# db/schema.rb
create_table "todos", charset: "utf8mb4", force: :cascade do |t|
  t.string "title"
  t.datetime "schedule_at"
  t.integer "status"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

# app/model/todo.rb
class Todo < ApplicationRecord
  enum status: { not_yet: 0, complete: 1, in_progress: 2, cancel: 3 }
end

Query

query_attribute

指定したattribute名の値が存在するかどうかを返却します。
[attribute名]?と同様の処理になります。
存在しないattribute名を指定するとNoMethodErrorの例外を吐きます。

todo = Todo.new
todo.query_attribute(:status) #=> false
todo.status? #=> false
todo.status = :not_yet
todo.query_attribute(:status) #=> true
todo.status? #=> true
# 存在しないattributeに対して実行するとNoMethodErrorの例外を吐く
todo.query_attribute(:error_attribute) #=> NoMethodError (undefined method `error_attribute'...

Read

read_attribute

指定したattributeの値を返却します。型キャストされた状態で値は返却されます。
attribute名はシンボルでも文字列でも指定可能です。

todo = Todo.new(schedule_at: '2021-02-02 22:22:22')
todo.read_attribute('schedule_at') #=> Tue, 02 Feb 2021 22:22:22.000000000 JST +09:00
todo.read_attribute(:schedule_at) #=> Tue, 02 Feb 2021 22:22:22.000000000 JST +09:00

Write

write_attribute

指定したattributeの値を更新します。
IntegerやFloatのカラムに対して空文字を指定した場合はnilに変換されます。
attributeの値を更新するだけで、UPDATE文が流れるわけではないのでお気をつけください。

todo = Todo.find(1) #=> #<Todo id: 1, title: "title", schedule_at: "2022-09-07 17:43:00.000000000 +0900", status: "not_yet", ...>
todo.write_attribute(:title, '') #=> #<Todo id: 1, title: "", schedule_at: "2022-09-07 17:43:00.000000000 +0900", status: "not_yet", ...>
# IntegerやFloatのカラムに対して空文字を指定した場合はnilに変換される
todo.write_attribute(:schedule_at, '') #=> #<Todo id: 1, title: "", schedule_at: nil, status: "not_yet", ...>
todo.write_attribute(:status, '') #=> #<Todo id: 1, title: "", schedule_at: nil, status: nil, ...>
todo.write_attribute(:status, 3) #=> #<Todo id: 1, title: "", schedule_at: nil, status: "cancel", ...>

おわりに

今回は、Query, Read, Writeメソッドについてまとめていきました。
正直なところ「直接attribute呼び出して処理したらええやん」という気持ちになったので、これらのメソッドのいい使い所があったら誰か教えてください。

その他のメソッドについては、別記事でまとめています。↓↓
ActiveRecord attribute methodまとめ(その①: BeforeTypeCast編)
ActiveRecord attribute methodまとめ(その②: Dirty編)
Active Record attribute methodまとめ(その③: PrimaryKey編)

参考

0
0
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
0
0