是否可以以散列格式编写此行(:created_at)
User.where("created_at > ?", Time.now - 1.month)
User.where("created_at >= ?", DateTime.parse('2012-10-31')
是否可以以散列格式编写此行(:created_at)
User.where("created_at > ?", Time.now - 1.month)
User.where("created_at >= ?", DateTime.parse('2012-10-31')
基本的 ActiveRecord 不支持。然而,底层查询生成库(称为 AREL)确实如此。然而,简单的 AREL 写起来相当不方便,这正是Squeel发挥作用的地方。它扩展了 ActiveRecord 并提供了扩展的 Ruby DSL 来指定条件。
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.