How can I rewrite the getter method in an ActiveRecord model?

I am trying to overwrite the getter method for the ActiveRecord model. I have a name attribute in the Category model, and I would like to do something like this:

 def name name_trans || name end 

If the name_trans attribute name_trans not nil, then return it, otherwise return the name attribute. How should I do it?

Then it should usually be called as follows:

 @category.name 
+72
ruby ruby-on-rails rails-activerecord getter-setter
Feb 17 '14 at 17:06
source share
7 answers

The Rails style guide recommends using self[:attr] over read_attribute(:attr) .

You can use it as follows:

 def name name_trans || self[:name] end 
+66
Feb 06 '15 at 9:44
source share

Update: The preferred method according to the Rails Style Guide is to use self[:name] instead of read_attribute and write_attribute . I would advise you to skip my answer and prefer this one instead.




You can do it this way, except that you need to use read_attribute to actually get the value of the name attribute and avoid recursively calling the name method:

 def name name_trans || read_attribute(:name) end 
+92
Feb 17 '14 at 17:09
source share

I would like to add another option to overwrite the getter method, which is simple: super.

 def name name_trans || super end 

this works not only with getter methods, but also with getter methods.

+8
May 01 '16 at 15:58
source share

Overriding the recipient and using read_attribute does not work for associations, but you can use alias_method_chain .

 def name_with_override name_trans || name_without_override end alias_method_chain :name, :override 
+4
Jun 12 '14 at 1:36 on
source share

If you use storage attributes like

 store :settings, accessors: [:volume_adjustment] 

or using gemstones hstore_accessor gem link

So, you have finished using the store method on the model, then override this method, which you cannot use self.read_attribute , you should use super instead:

 def partner_percentage super.to_i || 10 end 
+2
Sep 11 '15 at 6:50
source share

If someone wants to update the value after name_trans in the getter method, you can use self [: name] =.

 def name self[:name] = name_trans || self[:name] # don't do this, it will cause endless loop # update(name: name_trans) end 
0
Feb 07 '17 at 5:33
source share

You can use the Rails read_attribute method. Rails docs

0
Feb 17 '17 at 9:43 on
source share



All Articles