2

to_s我不想在我的模型中覆盖它,而是将其别名为一个名为full_name.

两者似乎都没有按预期工作aliasalias_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

8

弄清楚了...

alias并且alias_method需要在您使用别名的方法之后。

因此,以下两项都可以正常工作:

使用alias

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

  alias to_s full_name
end

# In Terminal
> Person.last.to_s  #=> "Don Draper"

使用alias_method

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

  alias_method :to_s, :full_name
end

# In Terminal
> Person.last.to_s  #=> "Don Draper"

希望这对其他人有帮助。

于 2014-04-22T16:28:18.127 回答