加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – TypeError:错误的参数类型Class(预期模块)

发布时间:2020-12-17 01:50:38 所属栏目:百科 来源:网络整理
导读:在app / models / abc / xyz.rb中 module Abc::Xyz extend ActiveSupport::Concernend 在app / models / abc.rb里面 class Abc ActiveRecord::Base include Abc::Xyz end 当我尝试从Abc.where(id:id)获取数据时,它有时会起作用,有时会返回此错误(TypeError
在app / models / abc / xyz.rb中

module Abc::Xyz
  extend ActiveSupport::Concern
end

在app / models / abc.rb里面

class Abc < ActiveRecord::Base
  include Abc::Xyz 
end

当我尝试从Abc.where(id:id)获取数据时,它有时会起作用,有时会返回此错误(TypeError:错误的参数类型Class(预期的模块)).

TypeError: wrong argument type Class (expected Module)
      app/models/abc.rb:2:in `include'
      app/models/abc.rb:2:in `<class:Abc>'
      app/models/abc.rb:1:in `<top (required)>'
      activesupport (3.2.17) lib/active_support/dependencies.rb:469:in `load'
      activesupport (3.2.17) lib/active_support/dependencies.rb:469:in `block in load_file'
      activesupport (3.2.17) lib/active_support/dependencies.rb:639:in `new_constants_in'
      activesupport (3.2.17) lib/active_support/dependencies.rb:468:in `load_file'
      activesupport (3.2.17) lib/active_support/dependencies.rb:353:in `require_or_load'
      activesupport (3.2.17) lib/active_support/dependencies.rb:502:in `load_missing_constant'
      activesupport (3.2.17) lib/active_support/dependencies.rb:192:in `block in const_missing'
      activesupport (3.2.17) lib/active_support/dependencies.rb:190:in `each'
      activesupport (3.2.17) lib/active_support/dependencies.rb:190:in `const_missing'
      activesupport (3.2.17) lib/active_support/inflector/methods.rb:230:in `block in constantize'
      activesupport (3.2.17) lib/active_support/inflector/methods.rb:229:in `each'
      activesupport (3.2.17) lib/active_support/inflector/methods.rb:229:in `constantize'
      activesupport (3.2.17) lib/active_support/core_ext/string/inflections.rb:54:in `constantize'

解决方法

我认为你最好坚持关于担忧的Rails惯例:

>使用模块来定义您的顾虑
>将问题置于app / models / Concer中

如果你想像Abc :: Xyz那样命名你的关注点,那么请确保你把它放在正确的路径:app / models / concerns / abc / xyz.rb.

另一个好点是

module Abc::Xyz

假设已经定义了模块Abc.如果没有它就会失败.所以也许你会更好地使用

class Abc
  module Xyz
    #...
  end
end

请注意,我使用了类Abc而不是模块,因为您的代码是隐含的.您不能同时拥有具有相同名称的类和模块.这也可能是你偶然发现错误的原因.请在Exploring Concerns上看到这篇精美的文章.

Rails尝试各种东西(自动)加载常量,但你最好坚持约定.我已经看到很多情况,由于定义/加载/执行常量的顺序,相同的代码片段在不同的时间点或不同的环境中失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读