2

モデルをオーバーライドする代わりにto_s、 という既存のメソッドにエイリアスを付けたいと思いfull_nameます。

aliasとの両方alias_methodが期待どおりに機能していないようです。

使用するalias

class Person < ActiveRecord::Base

  # ... other model code.

  alias to_s full_name

  def full_name
     "#{first_name} #{last_name}"
  end
end

# In Terminal
> Person.last.to_s  #=> "#<Person:0x007fa5f8a81b50>"

使用するalias_method

class Person < ActiveRecord::Base

  # ... other model code.

  alias_method :to_s, :full_name

  def full_name
     "#{first_name} #{last_name}"
  end
end

# In Terminal
> Person.last.to_s  #=> "#<Person:0x007fa5f8a81b50>"
4

1 に答える 1