How to override a column in Rails model? How to override a column in Rails model? ruby ruby

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)  endend


You can simply define a method of the same name as the column. To get the actual column value, use self[column_name]. So something like this should work:

class Dummy < ActiveModel::Base  def col_a    self[:col_a] % 10 == 0 ? 0 : self[:col_a]  endend

(This assumes col_a is an integer.)


I'm a little late to the party here, but a really elegant way to do it is to simply use super

class Dummy < ApplicationRecord  def col_a    super % 10 === 0 ? 0 : super  endend