ruby-on-rails - rails : Subclass not registering as instance of parent class

标签 ruby-on-rails ruby

在我正在使用的 Rails 应用程序中,我有如下代码:

# app/models/a.rb
class A < ActiveRecord::Base; ...; end
# app/models/b.rb
class B < A; ...; end

# /app/elsewhere...

do_case(B.new)

def do_case(letter)
  case letter
  when A
    "not nil"
  end
end

当我在本地运行它时,它按预期执行并且我得到“not nil”作为返回值。但是我在我的测试环境中得到了 nil

测试环境显示Aletter(B.new)的祖先(B.ancestors) code>), 但无法使用大小写相等运算符或 is_a?(A) 注册为子类。

A === B.new #=> false in test environment, true locally
B.new.is_a?(A)  #=> false in test environment, true locally

这似乎是一个 Rails 自动加载问题,但我不确定如果父类包含在两个环境的祖先中,为什么这些方法会失败。怎么回事?

最佳答案

同意,这看起来像是一个自动加载问题。虽然不理想,但您可以通过在 B 中添加 require_dependency 调用来解决它。

至于在哪里寻找根本问题,您的测试环境中可能有一些库依赖项在测试中不存在。我会在测试时加载 REPL 并检查 A。一些有用的方法:

class A
  def self.what_is_my_nesting
    Module.nesting
  end
end

A.what_is_my_nesting
A.ancestors
B.ancestors

等等

关于ruby-on-rails - rails : Subclass not registering as instance of parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884895/

相关文章:

python - 个性化统计类(class)的在线作业

ruby - Ruby 中有类似 null-stream 的东西吗?

ruby-on-rails - ActiveAdmin 选择过滤器集合

jquery - Rails 5 Bootstrap 崩溃不起作用

ruby-on-rails - 第三方库的单元测试

ruby - 如何理解#dup 和#clone 对引用其他对象的对象进行操作?

ruby-on-rails - 需要帮助解决失败的 Rspec 测试 - 参数错误 : Comparison of Date with nil

ruby-on-rails - rails : how to tell if Spring is loaded

ruby - 如何阻止类初始化程序在 Ruby 中打印对象?

mysql - 编写一个 Rails 事件记录查询来通过与两个表关联来获取所有项目?