什么code。在Rails是不是在运行时计算(即:ActiveRecord的范围,等等) [英] What code in Rails is not evaluated at runtime (ie: ActiveRecord scopes, etc)

查看:141
本文介绍了什么code。在Rails是不是在运行时计算(即:ActiveRecord的范围,等等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你试图评估当前日期的ActiveRecord的范围,它很可能是不正确的,由于这时候你的应用程序code加载,而不是在运行时进行评估。你必须在一个lambda通过这个通过,像这样:

If you try to evaluate the current date in an ActiveRecord scope, it will likely be incorrect due to this being evaluated when your application code is loaded instead of at runtime. You have to pass this through in a lambda, like this:

适用范围:今天,拉姆达{其中(:submitted_at => Date.today.to_time.utc ..(Date.today + 1).to_time.utc)}

scope :today, lambda { where(:submitted_at => Date.today.to_time.utc..(Date.today + 1).to_time.utc) }

这是一个时髦的例子,因为没有转换时间的发生。无论如何,我的问题是的还有什么地方,这是一个问题?的是ActiveRecord的作用域,我可以在我的电话,以日期算在运行时不被评估?唯一的地方

That is a funky example because there is conversion to time occurring. Regardless, my question is where else is this a concern? Are ActiveRecord scopes the only place where I can count on my calls to Date not being evaluated at runtime?

推荐答案

在声明范围我们在调用范围类本身的方法。这样做,就像你说的,在加载时间,而不是在运行时。

When you declare a scope you're calling the scope method on the class itself. This is done , as you said, in loading time and not in runtime.

这发生在每次调用的类的方法在其声明的时间。一些例子:

This happens every time you call a method on a class on its declaration. Some examples:

class Car < ActiveRecord::Base
  acts_as_combustion_machine
  belongs_to :driver
  has_many :wheels
end

这些都是方法的例子而其声明中被调用的类本身。这意味着它的任何参数将上装载时间,而不是在运行时间进行评价。

Those are examples of methods which are called on the class itself during its declaration. This means that any of its parameters will be evaluated on loading time and not on runtime.

让我们来进一步的例子。如果你想给引擎要用于 acts_as_combustion_machine 你可能做这样的事情:

Let's take a further example. If you wanted to give the engine to use for the acts_as_combustion_machine you'd maybe do something like:

acts_as_combustion_machine Engine.first

考虑到,这将在类加载时间(相同的日期)进行评估。

Take into account that this would be evaluated during class loading time (same as for the Date).

我想这可以帮助你澄清这一点的原因......但是,请不要犹豫,问是否有其他问题。我花了很有点明白这一点我自己;)

I guess it helps you clarifying the reason of this a bit more... but please, don't hesitate to ask if other questions. It took me a bit to understand this myself ;)

这篇关于什么code。在Rails是不是在运行时计算(即:ActiveRecord的范围,等等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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