Arel:需要帮助将 SQL 语句转换为 Rails 的 Arel 代码

Arel: Need help converting SQL statement into Arel code for Rails

试图让以下 SQL 在 Rails 查询中工作。

查询:

select addr.*
  from addresses addr
  join users u
    on addr.addressable_type = 'User'
   and addr.addressable_id = u.id
  join customers c 
    on c.id = u.actable_id
   and u.actable_type = 'Customer' 
 where c.account_id = 1
   and c.site_contact = 't'

这是我的 Rails 代码:

# Inside my account.rb model
def site_addresses
    a = Address.arel_table #Arel::Table.new(:addresses)
    u = User.arel_table #Arel::Table.new(:users)
    c = Customer.arel_table #Arel::Table.new(:customers)

    # trying to debug/test by rendering the sql. Eventually, I want
    # to return a relation array of addresses.
    sql = Address.
      joins(u).
        on(a[:addressable_type].eq("User").and(a[:addressable_id].eq(u[:id]))).
      joins(c).
        on(c[:id].eq(u[:actable_id]).and(u[:actable_type].eq("Customer"))).
     where(c[:account_id].eq(self.id).and(c[:site_contact].eq(true))).to_sql

    raise sql.to_yaml #trying to debug, I'll remove this later
  end
end

我收到类似 "unknown class: Arel::Table" 的错误。我没有正确使用 Arel,因为 SQL 代码有效(我可以 运行 它在数据库中就好了)

尝试以下操作:

a.join(u).on(a[:addressable_type].eq("User")... # Using the arel_table and "join" instead

我的回答基于 docs:

users.join(photos).on(users[:id].eq(photos[:user_id]))