Ricardo Green
Ricardo Green

Reputation: 1118

Rails: Using same name of Table field for Model method. Can this work?

Say I have a Users table with a first_name field. Automatically I have a User model.

What I wan't is to know if it is possible to make a method also named first_name in the User model work?

I might do some modification inside the method. Say the model and the method would look like this:

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

I'm getting SystemStackError: stack level too deep in the console. Just wanna know if this is possible or if this can work.

Upvotes: 4

Views: 2680

Answers (1)

deril
deril

Reputation: 101

You can use read_attribute method

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

Upvotes: 10

Related Questions