Custom attr_reader in rails

Basically in rails, if you write my_obj.attr, it looks attrin the database and reports it. How to create a custom method def attrthat internally queries the database for attr, modifies it, and returns? In other words, what is the missing piece here:

# Within a model. Basic attr_reader method, will later modify the body.
def attr
  get_from_database :attr   # <-- how do I get the value of attr from the db?
end
+3
source share
2 answers

Something like that:

def attr
  value = read_attribute :attr
  value = modify(value)
  write_attribute :attr, value
  save
  value
end
+3
source

The neutrino method is good if you want to save the changed value back to the database every time you get an attribute. This is not recommended, as it will perform an additional database query each time you try to read the attribute, even if it has not changed.

(, ), :

 def attr
   return read_attribute(:attr).capitalize #(or whatever method you wish to apply to the value)
 end
+1

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


All Articles