我有一个无数据库(无active_record
)Rails 4.2应用程序,其中包含两个使用ActiveModel::Model
模块的无表格模型。
(发布的代码已经过简化,但结果是真实的,无论如何。)
第一个模型:群组,在app/models/group.rb
中定义:
class Group
include ActiveModel::Model
def self.works?
true
end
end
一切都在app和控制台中都有效:
irb(main):001:0> Group.works?
=> true
irb(main):002:0> Group.instance_methods
=> [:model_name, :validation_context, :validation_context=, :_validate_callbacks, :_validate_callbacks?, :_validate_callbacks=, :_run_validate_callbacks, :_validators, :_validators?, :_validators=, :persisted?, :to_model, :to_key, :to_param, :to_partial_path, :validates_absence_of, :validates_acceptance_of, :validates_confirmation_of, :validates_exclusion_of, :validates_format_of, :validates_inclusion_of, :validates_length_of, :validates_size_of, :validates_numericality_of, :validates_presence_of, :run_callbacks, :errors, :valid?, :validate, :invalid?, :read_attribute_for_validation, :run_validations!, :validates_with, :blank?, :present?, :presence, :acts_like?, :duplicable?, :deep_dup, :try, :try!, :in?, :presence_in, :to_query, :instance_values, :instance_variable_names, :to_json_with_active_support_encoder, :to_json_without_active_support_encoder, :to_json, :as_json, :with_options, :html_safe?, :is_haml?, :psych_to_yaml, :to_yaml, :to_yaml_properties, :`, :require_or_load, :require_dependency, :load_dependency, :unloadable, :pretty_print, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :gem, :silence_warnings, :enable_warnings, :with_warnings, :silence_stderr, :silence_stream, :suppress, :capture, :silence, :quietly, :class_eval, :pretty_inspect, :byebug, :debugger, :concern, :suppress_warnings, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
第二个模型:横幅广告,在app/models/banner.rb
中定义,其代码与组中完全相同:
class Banner
include ActiveModel::Model
def self.works?
true
end
end
然而,这个不起作用:
irb(main):001:0> Banner.works?
NoMethodError: undefined method `works?' for Banner:Module (trace omitted)
irb(main):002:0* Banner.instance_methods
=> []
我已经尝试过对模型做过讨厌的事情,冗余地添加require "active_model"
(一些帖子表明这样的问题可能是由于类或类似物的延迟加载而产生的,这可能会解决它),并且直接复制 - 从一个模型到另一个模型的代码,只更改类名(如样本中),但没有运气。
答案 0 :(得分:2)
仔细阅读错误
NoMethodError: undefined method `works?' for Banner:Module
请参阅Banner:Module
?你有一些其他的Banner
,它是一个模块,它被加载代替你的模型(因此,遮蔽它)。
大多数情况下,这是由rails的延迟加载引起的。至于什么是补救措施,这取决于你的具体情况。常见的选择是: