2017-03-03 79 views
3

在我的postgres數據庫中,我有一個使用UUID的主鍵。下面如何在Arel中指定加入列

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 

當我嘗試獲取與支付的所有訪問樣本設置,我得到了一個錯誤:

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

基本上,這要求我明確投的visit.idvarchar,我可以很容易地做,如果我的加入聲明是一個字符串,通過:

connections.connectable_id = visits.id::varchar 

但是,我使用Arel的可組合性。

會有人指導,我怎麼能強制轉換這個與阿雷爾直接,所以我可以很容易地做一些事情,如:

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

雖然玩這個的時候,我發現了阿雷爾NamedFunction這基本上是一種在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)) 

這基本解決了我的問題!