LoginSignup
3
1

More than 3 years have passed since last update.

[Rails]テーブルから無作為で1つレコードが欲しい時 .sample使えた。

Posted at

課題と結論

テーブルから無作為にレコードが欲しいと思ったら普通に .sample使えました。

irb(main):005:0> User.all.sample(1)
=> [#<User id: 5, name: 'aho'>]

地味に知らなかった基礎。

参考情報

ActiveRecord::Relationとは一体なんなのか
https://doruby.jp/users/whale/entries/ActiveRecord--Relation%E3%81%A8%E3%81%AF%E4%B8%80%E4%BD%93%E3%81%AA%E3%82%93%E3%81%AA%E3%81%AE%E3%81%8B

3
1
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
3
1