Reputation: 37303
Trying to get the following SQL to work in a Rails query.
The Query:
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'
This is my Rails code:
# 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
I'm getting errors like "unknown class: Arel::Table". Im not using Arel correctly because the SQL code is valid (I can run it on the database just fine)
Upvotes: 0
Views: 1101
Reputation: 3638
Try the following:
a.join(u).on(a[:addressable_type].eq("User")... # Using the arel_table and "join" instead
I based my answer from the docs:
users.join(photos).on(users[:id].eq(photos[:user_id]))
Upvotes: 2