微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/266196.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐