Rails 3的活动记录关系顺序为:使用散列而不是字符串 [英] Rails 3 Active Record relation order: Use hash instead of string

查看:136
本文介绍了Rails 3的活动记录关系顺序为:使用散列而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要排序的Rails 3的关系,我们必须做到这一点:

To sort a relation in Rails 3, we have to do this:

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

但我觉得这样的:

But I think this:

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

会做出更好的意义,因为这样的字段名称进行转义应取决于适配器上( SqlLite VS VS的Mysql PostgreSQL的),对吧?

有没有类似的东西?

推荐答案

我认为,关键的问题是: ActiveRecord的API是不知道订货语义的。它只是接受一个字符串,并绕过底层数据库。幸运的是,SQLite的,MySQL和PostgreSQL在语法没有什么区别。

I think the key problem is: ActiveRecord API is not aware of ordering semantic. It just accepts a string and bypasses to the underlying database. Fortunately, Sqlite, MySQL and PostgreSQL has no difference in order syntax.

我不认为ActiveRecord的可以做到这一点抽象好,它并不需要这么做。它可以与关系数据库,但是很难与NoSQL的,例如集成。 MongoDB的。

I don't think ActiveRecord can do this abstraction well, and it doesn't need to do it. It works well with relation databases, but is hard to integrate with NoSQL, eg. MongoDB.

的DataMapper ,另一个著名的红宝石ORM,没有更好的抽象。 看看它的查询语法

DataMapper, another famous Ruby ORM, did better abstraction. Take a look at its query syntax:

@zoos_by_tiger_count = Zoo.all(:order => [ :tiger_count.desc ])

API是知道的排序语义。默认情况下,DataMapper的会生成SQL命令语句:

The API is aware of the ordering semantic. By default, DataMapper will generate SQL order statement:

https://github.com/datamapper/dm-do-adapter/blob/master/lib/dm-do-adapter/adapter.rb#L626-634

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

不过,它可能覆盖在DB接口层:

However, it's possible to override at DB adapter layer:

https://github.com/solnic/dm-mongo-adapter/blob/master/lib/dm-mongo-adapter/query.rb#L260-264

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


TL; DR:


TL;DR:

  • 您没有,如果你只使用SqlLite,MySQL和PostgreSQL需要担心语法问题。
  • 为了更好的抽象,你可以尝试DataMapper的。

这篇关于Rails 3的活动记录关系顺序为:使用散列而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆