Rails:对模型方法使用与表字段相同的名称。这能行吗?

Ric*_*een 3 ruby-on-rails ruby-on-rails-5.2

假设我有一个Users带有first_name字段的表。自动我有一个User模型。

我wan't是知道是否有可能使一个方法也被命名first_nameUser模式工作?

我可能会在方法内部做一些修改。假设模型和方法如下所示:

class User < ApplicationRecord
  def first_name
    # I know there are many ways to do this, this is just an example.
    "Mr. #{first_name}"
  end
end
Run Code Online (Sandbox Code Playgroud)

我正在进入SystemStackError: stack level too deep控制台。只是想知道这是否可行或是否可行。

小智 6

你可以使用read_attribute方法

class User < ApplicationRecord
  def first_name
    # I know there are many ways to do this, this is just an example.
    "Mr. #{read_attribute(:first_name)}"
  end
end
Run Code Online (Sandbox Code Playgroud)