2017-03-28 9 views
0

다음 SQL을 레일즈 쿼리에서 작동 시키려고합니다. Arel : 레일스 용 Arel 코드로 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' 

이 내 레일 코드 :

# 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 :: 테이블". 임 시도 SQL 코드가 유효하기 때문에 제대로

+0

어딘가 먼저 테이블을 나타내는 객체를 생성해야합니까? Like : address = Arel :: Table.new (: address)는 site_addresses 메소드에 있습니까? – bkunzi01

답변

2

(나는 잘 데이터베이스에서 실행할 수 있습니다) Arel를 사용하지 않는 다음

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

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

나는 docs에서 내 대답을 기반으로

+0

먼저, 코드 샘플에 괄호가 없습니다. 문제를 해결하려면 답변을 수정하십시오. 둘째로, 이것은 필자가 필요로하는 것에 가깝지만'Arel :: SelectManager' 객체를 가지고 있지만 액티브 레코드 :: 관계 객체로 변환하여 주소 배열을 돌려 줄 필요가 있습니다. 그걸 도와 줄 수있어? – DJTripleThreat

+0

오 죄송합니다. 코드를 지적하고있었습니다. ActiveRecord :: Relation을 사용하려면이 답변에서 지적한대로 코드를 다시 작성해야합니다. https://stackoverflow.com/questions/42840944/arel-active-relation-from-arelselectmanager-with-join –

+1

감사합니다. 이것은 도움이되었습니다! – DJTripleThreat