簡體   English   中英

Rails 自定義 ActiveRecord::Type 在 has_many 中使用 `class_name` 時失敗:通過關聯

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

我在 Rails 應用程序中使用KSUID作為 UUID 的替代品。 michaelherold/ksuid-ruby將 KSUID 移植到 Ruby 並將它們實現為::ActiveRecord::Type::String 除了使用has_many :through associations時的一個小錯誤has_many :through associationsclass_name結合的has_many :through associations時,一切都很好。

我能夠創建兩個 rspec 測試來演示該錯誤。

工作測試

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

未通過測試

當我更新患者的約會關聯以使用class_name它會導致TypeError: can't cast KSUID::Type

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)>'

你能幫我找出問題並修復測試嗎? 要重現自己,請運行:

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

這看起來像一個 Rails 錯誤。

當解析一個through關聯 ( patient.physicians ) 時,rails 會尋找一個與連接表名稱相同的關系,並且由於沒有 - 回退到字符串類型轉換(=不需要類型轉換,因此是錯誤)。

使示例工作的一個技巧是添加關系:

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) 合並了pull request 36847 ,修復了一些情況,並輸出了一個更容易理解的錯誤:

NotImplementedError:為了正確鍵入 cast Patient.id,Physician 需要定義一個 :appointments 關聯。

但它似乎打破了其他一些情況,因此不確定 6.1 版本中會出現什么。 所以現在上面的 hack 或帶有 rails 版本保護的猴子補丁看起來是一個可行的解決方案。

附注。 無論實際適配器是什么,您的ksuid/activerecord/schema_statementsPostgreSQLAdapter添加類型。

聚苯乙烯。 您可以使用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