LoginSignup
11
8

More than 5 years have passed since last update.

Mysql2::Error: Column 'created_at' in order clause is ambiguousの対策

Last updated at Posted at 2015-03-13

Railsのモデルで以下のように関連モデルをincludesしてタイトルのようなエラーがでたときの対策です。

book.rb

book = Book.includes(:author)
book = book.order("created_at DESC")

これだと以下のようなエラがでます。

Mysql2::Error: Column 'created_at' in order clause is ambiguous

これは、どのモデルのcreated_atか分からないよとおっしゃっているそうです。

なので、以下のようにテーブル名を明示すれば大丈夫です。

book.rb

book = Book.includes(:author)
book = book.order("books.created_at DESC")

以上ちょっとしたメモです。

11
8
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
11
8