简体   繁体   English

如何将数据按摩代码添加到模型属性?

[英]How can I add data-massaging code to a model attribute?

I'm working with a legacy database where a certain percentage value is stored in a DECIMAL column, but users enter and read the data as whole numbers. 我正在使用遗留数据库,其中某个百分比值存储在DECIMAL列中,但用户输入并读取整数数据。

So, let's say the DB includes... 所以,让我们说数据库包含......

contracts
---------
funded_percent DECIMAL 10,5

I'd like to add a "getter" and "setter" to the ActiveRecord model for that table multiply by 100 on read and divide by 100 on save. 我想在该表的ActiveRecord模型中添加一个“getter”和“setter”,在读取时乘以100并在保存时除以100。

The motivation is so that in my view code, I'm only dealing with whole numbers. 动机是这样的,在我的视图代码中,我只处理整数。

I'm not sure of the correct way to do that. 我不确定这样做的正确方法。


Oh, and some of the values go past three decimal places. 哦,有些值超过了小数点后三位。

So the method would need to round a stored value of "0.036" to a displayed value of "4%". 因此,该方法需要将存储的值“0.036”舍入到显示值“4%”。

here you refer to the attribute as "funded" to deal in whole numbers 在这里,您将属性称为“已资助”以处理整数

def funded=(other)
  self.funded_percent = other / 100
end

def funded
  funded_percent * 100
end

"0.036" to a displayed value of "4%". “0.036”到显示值“4%”。

You can use .round for this 你可以使用.round

def funded
  ( funded_percent * 100 ).round
end

Please try the following: 请尝试以下方法:

def funded_percent=(value)
  write_attribute :funded_percent, value/100 if value.present?
end

def funded_percent
  (read_attribute :funded_percent) * 100
end

Then in your view you could use funded_percent.ceil 然后在您的视图中,您可以使用funded_percent.ceil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 rails 代码添加到 div 标签中的 id 属性? - How can I add rails code to id attribute in div tag? 使用ActiveModel :: Serializer如何将表属性添加到每个模型 - Using ActiveModel::Serializer How Can I Add a table attribute to each model 如何从模型中的另一个虚拟属性覆盖属性? - How can i override an attribute from another virtual attribute in a model? 如何在RoR模型中为属性添加默认值? - How should I add a default value to an attribute in RoR model? Rails-如何将数据属性添加到fields_for select标签 - Rails - how can I add a data attribute to a fields_for select tag 如何使用Rails日期帮助器向每个选择项添加自定义数据属性? - How can I add a custom data attribute to each select using Rails date helper? 如何在Rails上的ruby上更改模型属性名称 - How I can change the model attribute name on ruby on rails 如何转换Rails引擎的模型和属性名称? - How can I translate model and attribute names of an Rails Engine? 如何从Rails模型中获取属性的数据类型? - How can I get the datatype of an attribute from a Rails model? 无法将多租户属性添加到嵌套模型 - Can't add multitenancy attribute to nested model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM