How to Override a Column in Rails Model

How to override a column in Rails model?

You can override the col_a method. Use the read_attribute method to read the value in database. Something like this:

def col_a
if self.read_attribute(:col_a).to_s.end_with?('0')
0
else
self.read_attribute(:col_a)
end
end

Overriding existing model in Rails 4

The keyword is "NoMethodError Exception: undefined method 'find_or_create_by' for ModelB:Module".

You have a module ModelB somewhere and, due to load order and/or constant lookup rules, it shadows your model.

Overriding or aliasing name of column in legacy database using Rails/ActiveRecord

I'm just kind of spitballing here, but you might try something like this:

class Legacy < ActiveRecord::Base
#... all the other stuff

#give yourself a way to access the DB version of object_id
def oid
attributes[:object_id]
end
def oid=(val)
attributes[:object_id]=val
end

#restore ruby's default #object_id implementation
def object_id
super
end
end

How can I overwrite a getter method in an ActiveRecord model?

The Rails Style Guide recommends using self[:attr] over read_attribute(:attr).

You can use it like this:

def name
name_trans || self[:name]
end


Related Topics



Leave a reply



Submit