Can I use set rails and getter for attributes for db columns

In rails, we can access the db column through the provided attribute rails, but can we change this? for example, I have db with a column with a name, I can implement something like.

def name
  "sir" + name
end

I tried, but this leads to a stack overflow. There is a way to do this.

more questions if there is a difference between the name and self.name.

+3
source share
3 answers
def name
  "sir" + read_attribute(:name)
end

But avoid this practice. Instead, use an optional getter / setter, also known as a "virtual attribute". Read this answer for more information: attribute decoration in rails

. . 3

"sir sir sir name"

,

def name
  n = read_attribute(:name)
  if /^sir/.match(name)
    n
  else
    "sir #{n}"
  end
end

, , .

+8

, , :

def name
  "sir" + self[:name]
end
+2

Use super

Ruby Override Methods

It has a lot of explanations, but I think it's as simple as calling a method that I already defined

def name
  "sir #{super}"
end
0
source

Source: https://habr.com/ru/post/1725708/


All Articles