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

时间:2017-03-28 11:01:28

标签: ruby-on-rails join relational-database predicate arel

尝试在Rails查询中使用以下SQL。

查询:

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代码是有效的(我可以在数据库上运行它就好了)

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

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]))