gpt4 book ai didi

ruby-on-rails - 在开发中运行 rails 控制台时,ActiveResource 添加了一个额外的类

转载 作者:行者123 更新时间:2023-12-04 15:17:54 27 4
gpt4 key购买 nike

我们有 2 个模型:估值和文档。两者都在微服务中,因此我们使用 ActiveResource 来访问它们。

class Valuation < ActiveResource::Base
self.site = "#{config.valuation_service.base_url}/valuations"
self.include_root_in_json = false
end

class Document < ActiveResource::Base
self.site = "#{config.valuation_service.base_url}/documents"
self.include_root_in_json = true
end

在开发中运行 Rails 控制台。
>> Valuation.new(documents: [{ title: 'Foo' }])
=> <Valuation:0x007f9af85f1708 @attributes={"documents"=>[#<Valuation::Document:0x007f9af85f0970 @attributes={"title"=>"Foo"}, @prefix_options={}, @persisted=false>]}, @prefix_options={}, @persisted=false>

所以文档的类名是 Valuation:Document .当您在生产环境中运行 rails 控制台时
>> Valuation.new(documents: [{ title: 'Foo' }])
=> <Valuation:0x007f9af595b478 @attributes={"documents"=>[#<Document:0x007f9af595a500 @attributes={"title"=>"Foo"}, @prefix_options={}, @persisted=false>]}, @prefix_options={}, @persisted=false>

文档的类只是 Document它尊重像 include_root_in_json 这样的配置.

更大的问题是在调用 .to_json 时在物体上。
# development
>> Valuation.new(documents: [{ title: 'Foo' }]).to_json
=> "{\"documents\":[{\"title\":\"Foo\"}]}"

# production
>> Valuation.new(documents: [{ title: 'Foo' }]).to_json
=> "{\"documents\":[{\"document\":{\"title\":\"Foo\"}}]}"

我们使用的是 Rails 4.2.10。

究竟是什么原因造成的?如果根据环境打开/关闭任何东西,我已经检查了配置,但我找不到任何东西。

最佳答案

ActiveResource 似乎正在使用 autoloading mechanism用于动态地将属性名称转换为集合的类。

正因为如此,开发和生产之间的差异是由于急切加载。在生产中,所有文件都是预先加载的,因此在您运行控制台时所有常量都已经存在。

当您在开发模式下运行控制台时,ActiveResource 会尝试为属性定义类名,但该机制不适用于您的用例。

如果 the constant is not found on Object , it is created within the class that is being initialized (Valuation)。

为了让开发以与生产相同的方式工作,您需要绕过触发此自动加载机制。这可以通过 require_dependency 轻松完成来自 Rails 的方法。

只需添加

require_dependency 'document'

class Valuation < ActiveResource::Base

Valuation 之前类,一切都应该正常工作。

此行确保 Document在任何人尝试创建 Valuation 的实例之前,已经加载了常量。类,并且不会使用自动加载机制。

关于ruby-on-rails - 在开发中运行 rails 控制台时,ActiveResource 添加了一个额外的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49665314/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com