1
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 3 years have passed since last update.

アソシエーションを組んでいる特定のレコードのカラムを取得する

Posted at

アソシエーションを組んでいる特定のレコードのカラムを取得する。
(最新のデータ編)

BEFORE

コントローラー
@last_asset = @account.assets.find(params[:id])

この記述でカラムのデータは取得できるようになったものの、求めている最新のデータは取得できずにいた。

自分なりの解決策

order('created_at DESC') を使って最新のデータを取得できるようにする。
これしか情報がなく、findメソッドとこの記述を合わせて使おうとしていたが、
どうも併用できないらしい。記述の仕方が悪かったのかもしれませんが。

 調べた結果

findではなく、find_byとorderなら併用できるようでしたので、メソッドの記述の順番を試行錯誤したら
答えにたどり着いた。

AFTER

コントローラー
@last_asset = @account.assets.order('created_at DESC').find_by(params[:id])
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?