要在 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/