2017-03-03 3 views
3

私のpostgresデータベースでは、私はUUIDを使って主キーを持っています。Arelに結合列を型キャストする方法

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

基本的にこれは私が明示的に場合、私は簡単に行うことができた、varcharvisit.idをキャストしている必要があります私は支払いを持つすべての訪問を取得しようとすると、私はエラーを得た

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 

以下のサンプルのセットアップ私の結合ステートメントは以下のように文字列でした:

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の[custom] 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)) 

そして、基本的には私の問題を解決しています!

関連する問題