2017-03-03 3 views
3

내 postgres db에 UUID를 사용하는 기본 키가 있습니다. 기본적으로이 내가 명시 적으로 visit.id 내가 쉽게 경우 할 수있는 varchar으로 캐스팅해야합니다Arel에 조인 열을 타입 변환하는 방법

Visit.joins(:payments) 
# => operator does not exist: character varying = uuid` 

:

class Visit 
# primary key id: uuid 
has_many :connections, as: :connectable 
has_many :payments, through: :connections 
end 

class Connection #(polymorphic class joining visit and payment) 
    # columns connectable_type(string), connectable_id(string) 
    belongs_to :payments 
    belongs_to :connectable, polymorphic: true 
end 

class Payment 
    # primary key id: uuid 
    has_many :connections 
end 

내가 지불 모든 방문을 인출하려고

아래 샘플 설정은, 오류가 발생했습니다 내 join 문은 다음과 같이 문자열입니다.

connections.connectable_id = visits.id::varchar 

그러나 합성 가능성을 위해 Arel을 사용하고 있습니다. 내가 직접 Arel 이것을 캐스트 할 수 있습니다, 그래서 쉽게 뭔가를 할 수있는 방법에 대한

수있는 사람이 가이드는 :

이 주변에 연주하는 동안, 나는 Arel NamedFunction에 대해 알게
join(connections_table).on(connections_table[:connectable_id].eq(cast_to_string(visits_table[:id]))) 
# where connections_table and visits_table are Arel tables 

답변

2

기본적으로 방법이다 Arel에서 [사용자 정의] SQL 함수를 랩핑합니다. 이 경우, 내가 함께 결국 :

casted_visits_primary_key = Arel::Nodes::NamedFunction.new("CAST", [ visits_table[:id].as("VARCHAR") ]) 

그리고 나는 할 수 있었다 :

join(connections_table).on(connections_table[:connectable_id].eq(casted_visits_primary_key)) 

을 그리고 기본적으로 내 문제를 해결!

관련 문제