使用 .build 时,ActiveStorage 动态服务无法访问关联
Steps to reproduce
(Guidelines for creating a bug report are available here)
Paste your executable test case created from one of the scripts found here below:
ruby
frozen_string_literal: true
require "bundler/inline" gemfile(true) do source "https://rubygems.org" gem "rails"
If you want to test against edge Rails replace the previous line with this:
gem "rails", GitHub: "rails/rails", branch: "main" gem "sqlite3" end require "active_record/railtie" require "active_storage/engine" require "minitest/autorun" ENV["DATABASE_URL"] = "sqlite3::memory:" class TestApp < Rails::Application config.load_defaults Rails::VERSION::STRING.to_f config.root = dir config.hosts << "example.org" config.eager_load = false config.session_store :cookie_store, key: "cookie_store_key" config.secret_key_base = "secret_key_base" config.logger = Logger.new($stdout) Rails.logger = config.logger config.active_storage.service = :eu_storage config.active_storage.service_configurations = { eu_storage: { root: Dir.tmpdir, service: "Disk" }, us_storage: { root: Dir.tmpdir, service: "Disk" } } config.active_job.queue_adapter = :inline end Rails.application.initialize! require ActiveStorage::Engine.root.join("db/migrate/20170806125915_create_active_storage_tables.rb").to_s ActiveRecord::Schema.define do CreateActiveStorageTables.new.change create_table :users, force: true do |t| t.string "location" end create_table :attachments, force: true do |t| t.integer "user_id" end end class User < ActiveRecord::Base has_many :attachments, inverse_of: :user enum :location, eu: :eu, us: :us end class Attachment < ActiveRecord::Base belongs_to :user, inverse_of: :attachments has_one_attached :file, service: ->(record) { record.storage_service_name } def storage_service_name user&.eu? ? :eu_storage : :us_storage end end class BugTest < ActiveSupport::TestCase def test_dynamic_service_with_association user = User.create!(location: :eu) # Working examples working_example = user.attachments.build working_example.assign_attributes( file: { content_type: "text/plain", filename: "dummy.txt", io: ::StringIO.new("dummy"), } ) assert_equal working_example.file.service.name, :eu_storage working_example2 = Attachment.create!( user_id: user.id, file: { content_type: "text/plain", filename: "dummy.txt", io: ::StringIO.new("dummy"), } ) assert_equal working_example2.file.service.name, :eu_storage # Failing examples failing_example = user.attachments.build( file: { content_type: "text/plain", filename: "dummy.txt", io: ::StringIO.new("dummy"), } ) assert_raises ActiveRecord::Errors::InvalidForeignKey do failing_example.save end end end
内容来源: rails/rails