1
0

orderとpluckを併用する時には記述する順番に気をつけようというお話

Last updated at Posted at 2024-08-12

あまり実用的なケースではないが、最新の一件のデータを取りたいがカラムはpluckしたい時に、クエリの呼び出し順に気をつけとかないと思うようなデータが取れないよというお話

試したコード

last_tweet = User.pluck(:userName, :tweetContent).order(created_at: "DESC").first

※コードは実際に使ったものを改変しています

発生したエラー

NoMethodError (undefined method `order' for an instance of Array):

解決策

last_tweet = User.order(created_at: "DESC").pluck(:userName, :tweetContent).first

シンプルにorderで並び替えてからpluckすれば仕様を満たすことができる
pluckしてからorderしようとしても該当のカラム(created_at)がないので並び替えることができない

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