0

是否可以以散列格式编写此行(:created_at)

User.where("created_at > ?", Time.now - 1.month) 
User.where("created_at >= ?", DateTime.parse('2012-10-31')
4

3 回答 3

2

基本的 ActiveRecord 不支持。然而,底层查询生成库(称为 AREL)确实如此。然而,简单的 AREL 写起来相当不方便,这正是Squeel发挥作用的地方。它扩展了 ActiveRecord 并提供了扩展的 Ruby DSL 来指定条件。

于 2012-11-03T18:54:53.273 回答
1

看看Squeel Gem

您将能够编写如Article.where{created_at >= 2.weeks.ago}文档中所示的代码。

它不完全是哈希格式,但它确实比您的示例更优雅。

于 2012-11-03T18:53:07.927 回答
0

I'm trying to get away from meta_where/squeel since it's not supported anymore. The only viable solution currently that I see, it's to dig into AREL:

User.where(User.arel_table[:created_at].gt(1.month.ago))
User.where(User.arel_table[:created_at].gteq(DateTime.parse('2012-10-31'))

You can put all your queries/scopes in a separate class from the model and encapsulate a lot of verbosity, look here:

You get a lot of benefit with this. All your scopes merging will work beautifully because arel will handle the aliasing for you.

On a personal note, I'm now in the Rails 3.0.20 ghetto because I rely heavily on meta_where that is not compatible with Rails 3.1+. I'm slowly replacing all the meta_where to arel.

于 2014-04-01T10:07:57.457 回答