有没有办法让ActiveRecord关系使用别名?

问题描述 投票:0回答:1

如果我有这样的模型

class MyTable < ActiveRecord::Base
  has_many :other_tables

  scope :my_scope, -> {
    select('t.id')
      .from('my_tables t')
      .where(...stuff)
      .other_complicated_scope
      .etc
  }
end

class OtherTable < ActiveRecord::Base
  belongs_to :my_table
end

因为范围使用表别名

t
,当我尝试使用内部联接时:

MyTable.joins(:other_table).my_scope

它会中断,因为它试图执行

INNER JOIN other_tables on other_tables.my_table_id = my_tables.id
而不是使用别名:
other_table.my_table_id = t.id

有没有办法告诉

joins
和其他关系方法使用别名而不是表名?

ruby-on-rails activerecord
1个回答
0
投票

我仍然不完全确定你想要完成什么 - 但我会开始重写你的范围如下:

class MyTable < ActiveRecord::Base
  has_many :other_tables

  scope :my_scope, -> {
    .where(...stuff)
    .other_complicated_scope
    .etc
  }
end

基本上就是在代码中省略“选择”。

在我的尝试中,我还改变了范围和加入:

MyTable.my_scope.joins(:other_table)

这至少对我的代码有用。

在相应的 Rails 指南中,您可以找到有关如何使用范围和条件的更多信息:https://guides.rubyonrails.org/active_record_querying.html#joining-tables

© www.soinside.com 2019 - 2024. All rights reserved.