加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4 – 如何在活动记录查询中给别的名称in

发布时间:2020-12-16 22:19:17 所属栏目:百科 来源:网络整理
导读:如何给出例如别名的别名?包括()? 以下给出: 用户:活动记录模型 学生:活动记录模式,继承自用户(STI) 老师:主动记录模式,继承自用户(STI) 项目:活动记录模式 这里有一些例子: 第一例(更多STI协会) Project.all.includes(:students,:teachers).order('t
如何给出例如别名的别名?包括()?
以下给出:

>用户:活动记录模型
>学生:活动记录模式,继承自用户(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读