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

関連付けたテーブルの取得時、特定のカラムでソートして取得する方法

1
Posted at

ユースケース

会社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 では上記の書き方で動いたので、備忘録として残しておく。

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?