ruby-on-rails – Rails 4 – 如何在活动记录查询中给别的名称in
如何给出例如别名的别名?包括()?
以下给出: >用户:活动记录模型 这里有一些例子: 第一例(更多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 这使用 现在您只需要在订单上使用(未经测试): 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(我第一次使用这种方法). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |