0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ActiveRecordRelationクラスの値を取得する方法

Posted at

記事概要

ActiveRecordRelationクラスの値を取得する方法について、記述する。
where句でレコードを取得した場合に活用できる。

言語やフレームワーク

使用技術
フロントエンド -
バックエンド Ruby 3.2.0
データベース -
インフラ -
API -
その他 -

データ取得方法

whre句を使用した場合のデータ取得方法

成功

irb(main):001> student = Student.where('id < 3')
  Student Load (2.3ms)  SELECT `students`.* FROM `students` WHERE (id < 3)
=> 
[#<Student:0x000000010c5a5908 id: 1, name: "Taro", age: 24, created_at: Sat, 16 Nov 2024 14:33:55.696305000 UTC +00:00, updated_at: Tue, 19 Nov 2024 16:34:25.414598000 UTC +00:00>,
 #<Student:0x000000010c5ea148 id: 2, name: "Jiro", age: 23, created_at: Sat, 16 Nov 2024 14:33:55.722352000 UTC +00:00, updated_at: Tue, 19 Nov 2024 16:34:25.434192000 UTC +00:00>]

irb(main):002> student.to_a[0].id
=> 1 
# 配列の0番目のidを取得

irb(main):003> student.to_a[0].name
=> "Taro"
# 配列の0番目のnameを取得

irb(main):004> student.to_a[1].name
=> "Jiro"
# 配列の1番目のnameを取得

エラー

student.idで値を取得しようとした場合、エラーが発生する。

irb(main):001> student = Student.where('id = 1')
  Student Load (2.0ms)  SELECT `students`.* FROM `students` WHERE (id = 1)
=> [#<Student:0x000000010713cfb0 id: 1, name: "Taro", age: 24, created_at: Sat, 16 Nov 2024 14:33:55.696305000 UTC +00:00, updated_at: Tue, 19 Nov 2024 16:34:25.414598000 UTC +00:00>]

irb(main):002> student.id
(irb):2:in `<main>': undefined method `id' for #<ActiveRecord::Relation [#<Student id: 1, name: "Taro", age: 24, created_at: "2024-11-16 14:33:55.696305000 +0000", updated_at: "2024-11-19 16:34:25.414598000 +0000">]> (NoMethodError)
Did you mean?  ids

findメソッドを使用した場合のデータ取得方法

irb(main):001> student = Student.find(1)
  Student Load (2.5ms)  SELECT `students`.* FROM `students` WHERE `students`.`id` = 1 LIMIT 1
=> #<Student:0x000000010e881328 id: 1, name: "Taro", age: 24, created_at: Sat, 16 Nov 2024 14:33:55.696305000 UTC +00:00, updated_at: Tue, 19 Nov 2024 16:34:25.414598000 UTC +00:00>

irb(main):002> student.id
=> 1

irb(main):003> student.name
=> "Taro"
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?