How to override a column in Rails model?

安稳与你 提交于 2020-01-28 04:48:06

问题


I have a model for one of my database tables. I want to override the column name for that particular table. How would I achieve it.

For example, let my table be called DUMMY and it has one column called col_a

col_a
20
34
42
23
12

I would be doing a @dummy.col_a. Now this method should return me 0 for numbers ending with 0 and for everything else, it should return the original value. I could do that by defining a new method, but I want to override the column name itself. Please help.


回答1:


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



回答2:


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]
  end
end

(This assumes col_a is an integer.)




回答3:


You can achieve that by overwriting default accessors as described in the documentation. All column values are automatically available through basic accessors on the Active Record object, but sometimes you want to specialize this behavior. This can be done by overwriting the default accessors (using the same name as the attribute) and calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things.

Scroll to the Overwriting default accessors section for more info.




回答4:


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
  end
end


来源:https://stackoverflow.com/questions/5909501/how-to-override-a-column-in-rails-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!