ruby-on-rails – Rails 4 – 如何在活动记录查询中给别的名称include()和join()

如何给出例如别名的别名?包括()?
以下给出:

>用户:活动记录模型
>学生:活动记录模式,继承自用户(STI)
>老师:主动记录模式,继承自用户(STI)
>项目:活动记录模式

这里有一些例子:

第一例(更多STI协会)

Project.all.includes(:students,:teachers).order('teachers_projects.name ASC') # order on teachers
Project.all.includes(:students,:teachers).order('users.name ASC') # order on students

Rails自动使用别名google_projects:sql中的老师.我如何覆盖这个,以便我可以在sql中使用别名名称老师而不是teacher_projects? :学生得到别名用户.

此示例失败:

Project.all.includes(:students,:teachers).order('teachers.name ASC')
Project.all.includes(:students,:teachers).order('students.name ASC')
Project.all.includes(:students,:teachers).order('students_projects.name ASC')

第二例(一个科技协会)

如果我只使用:方法中的学生(没有:老师)include(),Rails使用STI基类名用户名称别名(不附加_projects):学生:

Project.all.includes(:students).order('users.name ASC') # order on students

此示例失败:

Project.all.includes(:students).order('students.name ASC')
Project.all.includes(:students).order('students_projects.name ASC')

可能存在像:

Project.all.includes(:students).alias(students: :my_alias)

RAILS ALIAS追踪器

https://github.com/rails/rails/blob/v4.2.0/activerecord/lib/active_record/associations/alias_tracker.rb#L59

测试应用

https://gist.github.com/phlegx/add77d24ebc57f211e8b

https://github.com/phlegx/rails_query_alias_names

解决方法

我将采取另一种方法解决这个问题:而不是试图使用.alias方法来控制查询上的别名,我会让Rails / Arel处理它,只是看看正确的表名(别名或不是)只要在范围内需要它.

将此帮助方法添加到您的模型中,您可以从范围调用以了解范围是否在具有表名称别名(多个连接在同一个表上)的JOIN中使用,或者如果在另一个手的范围没有表名的别名.

def self.current_table_name
  current_table = current_scope.arel.source.left

  case current_table
  when Arel::Table
    current_table.name
  when Arel::Nodes::TableAlias
    current_table.right
  else
    fail
  end
end

这使用current_scope作为基础对象来查找arel表.我在该对象上调用source来获得一个Arel::SelectManager,这样就可以给你#left上的当前表.有两个选项:你有一个Arel :: Table(没有别名,表名在#name上),或者你有一个Arel :: Nodes :: TableAlias与其#right上的别名.

现在您只需要在订单上使用(未经测试):

Project.all.includes(:students,:teachers).order("#{current_table_name}.name ASC")
Project.all.includes(:students,:teachers).order("#{current_table_name}.name ASC")

相关问题:

> ActiveRecord query with alias’d table names(我第一次使用这种方法).
> Join the same table twice with conditions

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...