简体   繁体   English

Rails 自定义 ActiveRecord::Type 在 has_many 中使用 `class_name` 时失败:通过关联

[英]Rails custom ActiveRecord::Type fails when using `class_name` in has_many :through association

I'm using KSUIDs as a replacement for UUIDs in my Rails app.我在 Rails 应用程序中使用KSUID作为 UUID 的替代品。 michaelherold/ksuid-ruby ported KSUIDs to Ruby and implemented them as ::ActiveRecord::Type::String . michaelherold/ksuid-ruby将 KSUID 移植到 Ruby 并将它们实现为::ActiveRecord::Type::String Everything is working great except one little bug when using has_many :through associations combined with class_name .除了使用has_many :through associations时的一个小错误has_many :through associationsclass_name结合的has_many :through associations时,一切都很好。

I was able to create two rspec tests to demonstrate the bug.我能够创建两个 rspec 测试来演示该错误。

Working test工作测试

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast1_spec.rb#L50-L58 https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast1_spec.rb#L50-L58

# code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

bundle exec rspec ./spec/cast1_spec.rb # works as expected, tests pass

Failing test未通过测试

When I update Patient's appointment association to use class_name it will cause a TypeError: can't cast KSUID::Type .当我更新患者的约会关联以使用class_name它会导致TypeError: can't cast KSUID::Type

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast2_spec.rb#L46 https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast2_spec.rb#L46

# code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment" # <---- using class_name here
  has_many :physicians, through: :foobar
end

bundle exec rspec ./spec/cast2_spec.rb # test fails

TypeError:
  can't cast KSUID::Type
# ./spec/cast2_spec.rb:59:in `block (2 levels) in <top (required)>'

Can you help me find the problem and fix the test?你能帮我找出问题并修复测试吗? To reproduce yourself run:要重现自己,请运行:

git clone https://github.com/mattes/ksuid-ruby.git
cd ksuid-ruby
git checkout cast_error
bundle install
bundle exec rspec ./spec/cast1_spec.rb # works
bundle exec rspec ./spec/cast2_spec.rb # fails

This looks like a rails bug.这看起来像一个 Rails 错误。

When resolving a through -association ( patient.physicians ) rails looks for a relation named the same as join table, and since there's none - falls back to typecasting as a string (=no typecasting needed, thus the error).当解析一个through关联 ( patient.physicians ) 时,rails 会寻找一个与连接表名称相同的关系,并且由于没有 - 回退到字符串类型转换(=不需要类型转换,因此是错误)。

A hack to make the example work is to add the relation:使示例工作的一个技巧是添加关系:

class Physician < ActiveRecord::Base
  act_as_ksuid :id

  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # <= this is not used in app, but rails now can correctly resolve types
end

Rails master (6.1-alpha) has pull request 36847 merged, that fixes some cases and also outputs a more comprehensible error: Rails master (6.1-alpha) 合并了pull request 36847 ,修复了一些情况,并输出了一个更容易理解的错误:

NotImplementedError: In order to correctly type cast Patient.id, Physician needs to define a :appointments association. NotImplementedError:为了正确键入 cast Patient.id,Physician 需要定义一个 :appointments 关联。

But it appears to break some other cases , so it's uncertain what will come in 6.1 release.但它似乎打破了其他一些情况,因此不确定 6.1 版本中会出现什么。 So for now the above hack or monkey-patch with a rails version guard look like a viable solution.所以现在上面的 hack 或带有 rails 版本保护的猴子补丁看起来是一个可行的解决方案。

PS.附注。 your ksuid/activerecord/schema_statements adds type to PostgreSQLAdapter no matter what actual adapter is.无论实际适配器是什么,您的ksuid/activerecord/schema_statementsPostgreSQLAdapter添加类型。

PPS.聚苯乙烯。 you can use bundler/inline and minitest/autorun to create a self-contained example (runnable with just ruby filename.rb ):您可以使用bundler/inlineminitest/autorun来创建一个自包含的示例(只需ruby filename.rb运行):

require 'bundler/inline'

gemfile(ENV['INSTALL']=='1') do
  source 'https://rubygems.org'
  gem 'activerecord', '~>6.0.2' # also tested '~>5.2', '5.0' with same result, master with different error
  gem 'sqlite3' # use , '~> 1.3.6' # for rails 5
  gem 'ksuid', github: 'mattes/ksuid-ruby', ref:'e545b1b251bd6430c454509475963a7845b1da0f'

  gem 'minitest'
end

require "active_record"
require "logger"

require "ksuid/activerecord"
require "ksuid/activerecord/table_definition"

# require "rails"
# require "ksuid/activerecord/schema_statements" # commented out to not load rails only to check Rails.env, instead:
require "active_record/connection_adapters/sqlite3_adapter"
::ActiveRecord::ConnectionAdapters::SQLite3Adapter::NATIVE_DATABASE_TYPES[:ksuid] = { name: "varchar", limit: 27 }

# require "ksuid/activerecord/quoting" # monkey-patch that fixes the error


ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(IO::NULL)
ActiveRecord::Schema.verbose = false

ActiveRecord::Schema.define do
  create_table(:physicians,   force: true, id: :ksuid)
  create_table(:patients,     force: true, id: :ksuid)
  create_table(:appointments, force: true, id: :ksuid) {|t| t.ksuid :physician_id, :patient_id }
end

class Physician < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # the hack
end

class Appointment < ActiveRecord::Base
  act_as_ksuids :id, :physician_id, :patient_id
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)

require "minitest/autorun"

describe "ActiveRecord integration" do
  it "loads all associations correctly" do
    patient = Patient.create!
    physician = Physician.create!
    appointment = Appointment.create!(patient_id: patient.id, physician_id: physician.id)
    expect(patient.id.class).must_equal KSUID::Type

    expect(patient.physicians.first).must_equal physician
    expect(physician.patients.first).must_equal patient
  end
end

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

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