LoginSignup
1

More than 3 years have passed since last update.

rails6から追加されるActiveRecord::Base#implicit_order_column

Posted at

ActiveRecord::Base#implicit_order_column

first, lastなどの順序付けられたfinderメソッドを呼び出す時にActiveRecordは主キーで暗黙のソートを行います。UUIDなどの自動インクリメント整数ではないカラムが主キーに指定されていると問題が発生するので、暗黙のソートに使用される列をオーバーライドが可能になります。

参考

rails\activerecord\CHANGELOG.md
*   Make the implicit order column configurable.
    When calling ordered finder methods such as +first+ or +last+ without an
    explicit order clause, ActiveRecord sorts records by primary key. This can
    result in unpredictable and surprising behaviour when the primary key is
    not an auto-incrementing integer, for example when it's a UUID. This change
    makes it possible to override the column used for implicit ordering such
    that +first+ and +last+ will return more predictable results.

    Example:

        class Project < ActiveRecord::Base
          self.implicit_order_column = "created_at"
        end

rails\activerecord\lib\active_record\model_schema.rb
      def ordered_relation
        if order_values.empty? && (implicit_order_column || primary_key)
          order(arel_attribute(implicit_order_column || primary_key).asc)
        else
          self
        end
      end

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