如何在Arel中指定加入列
问题描述:
在我的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.id
到varchar
,我可以很容易地做,如果我的加入声明是一个字符串,通过:
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
答
虽然玩这个的时候,我发现了阿雷尔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))
这基本解决了我的问题!