2
2

More than 1 year has passed since last update.

【Rails】has_manyにデフォルトでorderを設定する

Posted at

実装方法

UserモデルにPostモデルが紐づくとします。
並び替えは作成日時の降順(新しい順)です。

class User
  has_many :posts, -> { order(created_at: :desc) }, dependent: :destroy
end

注意いただきたいのは、dependent: :destroyはorderの後ろに書くということです。

2
2
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
2
2