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?

More than 1 year has passed since last update.

ActiveRecord_Relationクラス 配列のように扱える

Posted at

配列のように表示された。

irb(main):071:0> a = User.where("name LIKE ?", "t%")
  User Load (0.9ms)  SELECT `users`.* FROM `users` WHERE (name LIKE 't%')
=>                                   
[#<User:0x000000010f2a5138 ...    
irb(main):072:0> a
=> 
[#<User:0x000000010f2a5138 
  id: 98,                  
  name: "tarou",           
  email: "aaa@aaa",        
  password_digest: nil,    
  user_image: nil,         
  updated_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00,
  created_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00>,
.
.
.
#<User:0x000000010f2a4d50
  id: 103,
  name: "tarou",
  email: "iii@iii",
  password_digest: nil,
  user_image: nil,
  updated_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00,
  created_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00>]

クラスは?

irb(main):073:0> a.class
=> User::ActiveRecord_Relation

配列のように呼び出せる。

irb(main):074:0> a[0]
=> 
#<User:0x000000010f2a5138                            
 id: 98,                                             
 name: "tarou",                                      
 email: "aaa@aaa",                                   
 password_digest: nil,                               
 user_image: nil,          
 updated_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00,
 created_at: Sat, 01 Jan 2000 00:00:00.000000000 UTC +00:00>

長さを調べることができる。

a.length
=> 6

joinで文字列の結合もできる。

irb(main):095:0> a.join(",")
irb(main):096:0*   
=> "#<User:0x000000010f2a5138>,#<User:0x000000010f2a5070>,#<User:0x000000010f2a4fa8>,#<User:0x000000010f2a4ee0>,#<User:0x000000010f2a4e18>,#<User:0x000000010f2a4d50>"  

感想

これからこれを知っておくことは重要な気がする。
このクラス以下は配列のように扱うのか。
まだ知らないことがたくさんある。
これから勉強だ。

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?