ユースケース
会社companiesモデルと、社員employeesモデルがあって、一対多の関係を設定済み。
companiesモデルの取得時に、employeesモデル側をidカラムではなくnumberカラム順で取得したい。
ダメな例
はじめは以下のように書いた(どこかのサイトの記事を参考にして)
class Company < ApplicationRecord
...中略...
has_many :employees, order: 'number'
すると、以下のように「そんなキーないですよ」と怒られます。
Unknown key: :order. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
正しい例
正しくは以下。
class Company < ApplicationRecord
...中略...
has_many :employees, -> { order(:number) }
古い記事だったからかもしれないが、とりあえず 5.0.0 では上記の書き方で動いたので、備忘録として残しておく。