wha*_*ver 5 ruby enums ruby-on-rails
我正在尝试调试运行bundle exec rake
任务时出现的一些错误。
ArgumentError: You tried to define an enum named "catalogue" on the model "CollectionContext", but this will generate a instance method "museum?", which is already defined by another enum.
Run Code Online (Sandbox Code Playgroud)
SO 有很多与此问题相关的问题,但所有问题似乎都归结为同一模型中不同枚举使用相同的值,这可以通过使用 _suffix 或 _prefix 来解决。
这是 Rails 中枚举用法的精彩解释https://naturally.com/blog/ruby-on-rails-enum
就我而言,我在模型中看不到重复项。如何进一步调试错误?
class CollectionContext < ActiveRecord::Base
include Authority::Abilities
self.authorizer_name = 'ManagedContentAuthorizer'
has_many :context_sets, inverse_of: :collection_context
has_many :museum_collections, through: :context_sets,
source: :contextable,
source_type: 'MuseumCollection'
enum catalogue: %i[museum archive library]
enum vocabulary: {category: 10,
collection: 20,
concept: 30,
event: 40,
gallery: 50,
material: 60,
organisation: 70,
people: 80,
person: 90,
place: 100,
style: 110,
technique: 120}
validate :check_multiple
def check_multiple
if [identifier, query, query_url].compact.count != 1
errors[:base] << " cannot set multiple context links"
end
end
end
Run Code Online (Sandbox Code Playgroud)
我现在发现,如果我在 Rails 环境设置为 TEST 的情况下运行 rake,它不会在控制台中显示任何问题。所以这只是一个发展问题。我已经用我的 gemfile 进行了实验,并将所有仅用于开发的 gem 放入开发和测试组中,但在开发中运行 rake 时仍然出现错误。
这是我的 config/development.rb 文件
# frozen_string_literal: true
Rails.application.configure do
config.webpacker.check_yarn_integrity = false
config.cache_classes = false
config.eager_load = false
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.active_record.migration_error = :page_load
config.assets.debug = true
config.assets.digest = true
config.assets.raise_runtime_errors = true
config.web_console.whitelisted_ips = '10.xxxx'
end
Run Code Online (Sandbox Code Playgroud)
可能与弹簧或其他类似的东西运行有关。尝试使用 DISABLE_SPRING=1 启动开发或仅删除弹簧。
其他可能性包括有一个名为 的布尔列,museum
该列是该museum?
方法的来源以及一些我们看不到的其他代码。
在调试方面,我只需打开 Rails,其中堆栈跟踪指向引发的错误,并使用内省来查看检测到的现有方法的定义位置?当然,工具带中还有其他工具,例如 method_added 和tracepoint,但我喜欢“查找它的引发位置并执行”method(:museum?).source_location
之类的功能。
为了避免在 Rails 应用程序中重新评估枚举行,我经常将其定义为:
enum catalogue: %i[museum archive library] unless method_defined?(:museum?)
Run Code Online (Sandbox Code Playgroud)