【问题标题】:How to typecast a join column in Arel如何在 Arel 中对连接列进行类型转换
【发布时间】:2017-07-23 21:54:17
【问题描述】:

在我的 postgres 数据库中,我有一个使用 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

当我尝试通过付款获取所有访问时,出现错误:

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

基本上,这要求我将visit.id 显式转换为varchar,如果我的连接语句是字符串,我可以很容易地做到这一点:

connections.connectable_id = visits.id::varchar

但是我使用 Arel 来实现可组合性。

任何人都可以指导我如何直接使用 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

【问题讨论】:

    标签: ruby-on-rails ruby postgresql activerecord arel


    【解决方案1】:

    在玩这个的时候,我发现了 Arel 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))
    

    这基本上解决了我的问题!

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      相关资源
      最近更新 更多