1
1

More than 1 year has passed since last update.

#Rails ( ActiveRecord ) で alias / alias_method がエラーを起こすので alias_attribute を使う

Last updated at Posted at 2020-04-14

Class

class User < ApplicationRecord
  alias_attributes :some_name, :name
end

run example

User.last.name
# Alice

User.last.alias_name
# Alice

Error case ( alias / alias method )


  alias foo_alias_name name
  # NameError: undefined method `name' for class `User (call 'User.connection' to establish a connection)'

  alias_method :bar_alias_name, :name
  # NameError: undefined method `name' for class `User (call 'User.connection' to establish a connection)'

Why?

  • alias / alias_method が使えないのは評価順、ActiveRercord的なメソッド生成タイミングの問題と思われる
  • ActiveRecord によってメソッド生成されたあとにOpenClass すると alias をつけることも出来る様子

Open class
Before ActiveRecord Model methods occur

class User
  alias alias_name name
end
# NameError: undefined method `name' for class `User'

Open class
After ActiveRecord Model methods occur

User.first # Maybe ActiveRecord method occurs in this timing

class User
  alias alias_name name
end

User.first.alias_name
# => "Alice"

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
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
1
1