0
1

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.

Active Record のアソシエーション(has_many, belongs_to)に条件を付けるときは一番最初の引数に lambda を渡さなければならない

Posted at

概要

Active Record のアソシエーション(has_many, belongs_to)に条件付けをしたはずなのに、その条件が動作しない場合があるので共有です。

方法

下記のように lambda を最後に記載すると where は動作しないが

has_many :comments, { class_name: 'Comment' }, -> { order(id: :asc) }

一番最初に記載すると正常に動作します。

has_many :comments, -> { order(id: :asc) }, { class_name: 'Comment' }
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?