ruby-on-rails - Rails 3 Active Record 关系顺序 : Use hash instead of string

标签 ruby-on-rails ruby activerecord ruby-on-rails-3.1

要在 Rails 3 中对关系进行排序,我们必须这样做:

User.where(:activated => true).order('id ASC')

但我认为:

User.where(:activated => true).order(:id => :asc)

会更有意义,因为转义字段名称的方式应该取决于适配器(SqlLite vs Mysql vs PostgreSQL),对吧?

有类似的东西吗?

最佳答案

据我所知,ActiveRecord 中没有内置此语法的选项,但添加一个应该不难。我在 lib/active_record/relation/query_methods.rb 中找到了 order 方法。理论上,你应该能够做这样的事情:

module ActiveRecord
  module QueryMethods
    def order(*args)
      args.map! do |arg|
        if arg.is_a? Hash
          # Format a string out of the hash that matches the original AR style
          stringed_arg
        else
          arg
        end
      end

      super
    end
  end
end

关于ruby-on-rails - Rails 3 Active Record 关系顺序 : Use hash instead of string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8138008/

相关文章:

mysql - 事件记录二级关联和按计数分组

ruby-on-rails - 测试 ApplicationController 过滤器、Rails

javascript - 在 Backbone 中渲染下拉菜单

html - rails haml span 正在结束 "early"- 为什么?

ruby-on-rails - 与同一事物的多种关系 Rails

ruby-on-rails - rails ActiveRecord : Multiple conditions in find

ruby-on-rails - 如何使用云端的 s3 对象 URL?

ruby - 需要 : command not found

ruby-on-rails - 在不是按字母顺序排列的情况下按尺寸名称订购商品?

ruby-on-rails - 博客文章的简单模型