试图让以下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
我收到诸如"未知类:Arel::Table"之类的错误。我没有正确使用Arel,因为SQL代码是有效的(我可以在数据库上运行它(
尝试以下操作:
a.join(u).on(a[:addressable_type].eq("User")... # Using the arel_table and "join" instead
我根据文档给出了答案:
users.join(photos).on(users[:id].eq(photos[:user_id]))