轨道3,模型方法/计算属性 [英] Rails 3, Model Methods / Calculated Attributes

查看:92
本文介绍了轨道3,模型方法/计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与众多的计算处理,以在模型中带来的各种值,以一个简单的TRUE或FALSE。问题是,这些计算是pretty的激烈,这也不是我想创建一个漫长而艰难的跟踪SQL语句。我宁愿只是有一个方法,在整个计算,该模型可以检查返回记录时进行。

我已经试过许多办法可以做到这一点,查找其他类似壮举的时候,别人推newbs像我这样的SQL这可能会成为大多数用途,但不会成为我的作为计算正在做有点模型的外部。

型号:

 类质量与LT;的ActiveRecord :: Base的
...
高清passed_inspection
   [code,计算基于数值模型]
结束
 

控制器:

  @records = Quality.wh​​ere('passed_inspection =真)
 

查看:

 有没有检验合格?:<%= record.passed_inspection%>
 

解决方案

这听起来像问题的解决方案是使用一个范围类方法以帮助清理你的模型。从本质上讲,你将建立你的模型是这样的:

 类质量与LT;的ActiveRecord :: Base的
    高清self.passed_inspection
        #code,做你的计算
    结束

    适用范围:通过,passed_inspection()#这需要了以下功能上面
结束
 

然后,你可以调用它像这样得到这个数据。

  @records = Quality.passed
 

有投这个问题,如果你需要更多的信息,一个扶手: RailsCast#215高级查询

编辑:修正了一些可怕的语法

I am dealing with numerous calculations to bring various values within a model to a simple TRUE or FALSE. Problem is, these calculations are pretty intense and not something I want to create a long, hard to follow SQL statement for. I'd rather just have the entire calculation within a method that the model could check for when returning records.

I've tried numerous ways to accomplish this, and when looking up other similar feats, others push newbs like me to SQL which might serve most purposes but will not serve mine as the calculations being done are somewhat external to the model.

Model:

class Quality < ActiveRecord::Base
...
def passed_inspection
   [code that calculates based on values in model]
end

Controller:

@records = Quality.where('passed_inspection = true')

View:

Did pass inspection?: <%= record.passed_inspection %>

解决方案

It sounds like the solution to your problem would be to use a Scope with a Class Method to help clean up your model. Essentially you would set up your model like this:

class Quality < ActiveRecord::Base
    def self.passed_inspection
        # Code that does your calculations
    end

    scope :passed, passed_inspection() # This needs to be below the function above
end

Then you could get this data by calling it like this

@records = Quality.passed

There is a rails cast about this problem if you need any more information: RailsCast #215 Advanced Queries

Edit: Fixed some terrible grammar

这篇关于轨道3,模型方法/计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆