Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 317
Ricardo Green Avatar asked Oct 24 '25 10:10

Ricardo Green


1 Answers

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
like image 109
deril Avatar answered Oct 26 '25 03:10

deril



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!