简体   繁体   English

使用自定义 ActiveRecord::Type(二进制)列时,“has_many through”关联不起作用

[英]“has_many through” association doesn't work when using a custom ActiveRecord::Type (binary) column

I've created the following ActiveRecord type and while has_many associations work well, has_many :through don't:我创建了以下ActiveRecord 类型,虽然has_many关联工作良好,但has_many :through不:

# app/types/uuid_type.rb
class UuidType < ActiveRecord::Type::Binary
  def serialize(value)
    super(cast_to_uuid(value)&.raw)
  end

  def deserialize(value)
    cast_to_uuid(super(value)).to_s
  end

  def cast_value(value)
    cast_to_uuid(value).to_s
  end

  private

  def cast_to_uuid(value)
    return if value.nil?

    case value.size
    when 16 then UUIDTools::UUID.parse_raw(value) # From `uuidtools` gem
    when 36 then UUIDTools::UUID.parse(value)     # From `uuidtools` gem
    end
  end
end

# app/models/token.rb
class Token < ActiveRecord::Base
  attribute :id, UuidType.new, default: SecureRandom.uuid

  has_many :token_users
  has_many :users, through: :token_users
end

(I've also written an entire code to replicate the issue ). (我还编写了完整的代码来复制该问题)。


The SQL where clause generated for has_many is similar to the following and works perfectly:has_many生成的 SQL where子句类似于以下内容并且完美运行:

WHERE column = x'4e254953bcdb4793a485ac04131565a7'

While the one generated for has_many :through does not work:虽然为has_many :through生成的has_many :through不起作用:

WHERE column = '4e254953-bcdb-4793-a485-ac04131565a7'

It doesn't return any error, but also doesn't return any results .它不返回任何错误,也不返回任何结果

The problem is that the second one ( has_many :through ) doesn't include the x prefix and also doesn't remove the hyphens (If I manually do that, it solves the issue).问题是第二个( has_many :through )不包含x前缀,也不删除连字符(如果我手动这样做,它解决了问题)。

I was able to replicate the issue with both MySQL and SQlite and both Rails 5 and 6 .我能够用MySQLSQlite以及Rails 56复制这个问题。

Why does the has_many :through relationship not produce the same SQL for a binary type?为什么has_many :through关系不会为二进制类型生成相同的 SQL? And how can you get it working so that it does?你怎样才能让它工作呢?

It turns out that it was a Rails bug.事实证明这是一个Rails错误。

I've submitted an issue on the official repo and they've fixed it:我已经在官方 repo 上提交了一个问题,他们已经修复了它:

👉 https://github.com/rails/rails/pull/36847 👉 https://github.com/rails/rails/pull/36847

我不确定它是否会有所帮助,但转到 config/initializers/type.rb 并添加

ActiveRecord::Type.register(:token_users, UuidType)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM