【发布时间】:2022-01-22 18:25:21
【问题描述】:
有没有办法在单个作用域的上下文中为源表设置别名?
我试过了:
scope = User.all
scope.arel.source.left.table_alias = "toto"
scope.where(firstname: nil) => "SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`firstname` IS NULL"
问题是模型类为所有后续查询保留别名:
User.all => "SELECT `toto`.* FROM `users` `toto`"
编辑
我把这个方法加到ApplicationRecord
def self.alias_source(table_alias)
klass = Class.new(self)
klass.all.source.left.table_alias = table_alias
klass
end
现在,我可以做:
User.alias_source(:toto).where(firstname: nil) => "SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`firstname` IS NULL"
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-5 arel