Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 3活动记录关系顺序:使用哈希而不是字符串_Ruby On Rails_Ruby_Activerecord_Ruby On Rails 3.1 - Fatal编程技术网

Ruby on rails Rails 3活动记录关系顺序:使用哈希而不是字符串

Ruby on rails Rails 3活动记录关系顺序:使用哈希而不是字符串,ruby-on-rails,ruby,activerecord,ruby-on-rails-3.1,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中没有内置此语法的选项,但添加一个应该

要对Rails 3中的关系进行排序,我们必须执行以下操作:

User.where(:activated => true).order('id ASC')
但我认为:

User.where(:activated => true).order(:id => :asc)
这样会更有意义,因为字段名的转义方式应该取决于适配器(
SqlLite vs Mysql vs PostgreSQL
),对吗


有类似的东西吗?

据我所知,ActiveRecord中没有内置此语法的选项,但添加一个应该不难。我找到了
lib/active\u record/relation/query\u 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

我认为关键问题是:ActiveRecordAPI不知道排序语义。它只接受一个字符串并绕过底层数据库。幸运的是,Sqlite、MySQL和PostgreSQL在
order
语法上没有区别

我认为ActiveRecord不能很好地完成这个抽象,它也不需要这样做。它与关系数据库配合得很好,但很难与NoSQL集成,例如MongoDB

另一个著名的Ruby ORM做得更好

API知道排序语义。默认情况下,DataMapper将生成SQL order语句:

def order_语句(顺序、限定)
语句=order.map do |方向|
语句=属性到列名称(direction.target,qualify)

语句对于这种特殊情况,您可以删除'ASC'位,因为所有数据库中的排序都是隐式升序的

Foo.order(:bar)
我知道这并不包括您希望按bar desc执行排序的情况,但实际上,对于按排序的情况,这并不重要,除非您对order by子句使用函数,在这种情况下,类似的操作可能会有所帮助

def order_statement(order, qualify)
  statements = order.map do |direction|
    statement = property_to_column_name(direction.target, qualify)
    statement << ' DESC' if direction.operator == :desc
    statement
  end

  statements.join(', ')
end
def sort_statement(conditions)
  conditions.inject([]) do |sort_arr, condition|
    sort_arr << [condition.target.field, condition.operator == :asc ? 'ascending' : 'descending']
  end
end
Foo.order(:bar)