简体   繁体   English

rails模型的动态属性

[英]dynamic attribute for a rails model

I'm wondering what is the best way to achieve what I want :p 我想知道实现我想要的最好方法是什么:p

I have a model 'ModelA' which has many 'ModelARate'. 我有一个模型'ModelA',它有许多'ModelARate'。 ModelARate contains a comment or a rate (or both). ModelARate包含注释或速率(或两者)。

I don't want to calculate the average rate each time a ModelA is shown. 我不想在每次显示ModelA时计算平均费率。 Because it's not cool for the database (accessing all ModelARate and getting rate ...) I need to know also the lowest and the highest rate. 因为它对数据库来说并不酷(访问所有ModelARate并获得速率......)我还需要知道最低和最高速率。

How is the best way to achieve this in rails ? 在rails中实现这一目标的最佳方法是什么? (without using a gem, I need to understand how it actually works) (不使用宝石,我需要了解它是如何工作的)

I was thinking of adding a attribute rate_score in ModelA which is increasing when a ModelARate is created, and a method which return rate_score / modelarates.size For the lowest and highest rate, an attribute too ? 我想在ModelA中添加属性rate_score,它在创建ModelARate时增加,并且返回rate_score / modelarates.size的方法对于最低和最高速率,属性也是? There is no mechanism that can do this for me in rails ? 在rails中没有可以为我做这个的机制吗?

Thanks for any help 谢谢你的帮助

You can use the calculation method on Rails http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html 您可以在Rails上使用计算方法http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html

For your models, given a ModelA record, you can 对于您的模型,给定ModelA记录,您可以

maximum = model_a.model_a_rates.maximum(:rate)
minimum = model_a.model_a_rates.minimum(:rate)
average = model_a.model_a_rates.average(:rate)

all of these calculations are done on the sql server so they are very fast so there's no need for you to worry about speed. 所有这些计算都是在sql server上完成的,所以它们非常快,所以你不必担心速度。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM