ruby-on-rails – 如何解决`对象不支持#inspect`错误?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何解决`对象不支持#inspect`错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用rails v3.2.2,当我尝试加载相关记录时,我收到一个奇怪的错误.

以下是我得到的终端输入/输出

1.9.2-p318 :011 > Category.first
=> #<Category id: 1,...>

1.9.2-p318 :013 > Category.first.articles
  Article Load (0.2ms)  SELECT `articles`.* FROM `articles` LIMIT 1
(Object doesn't support #inspect)

1.9.2-p318 :014 > Category.first.articles.first
  Category Load (0.2ms)  SELECT `categories`.* FROM `categories` LIMIT 1
NoMethodError: undefined method `scoped' for Category::Article:Module
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/association.rb:123:in `target_scope'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/through_association.rb:15:in `target_scope'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/association.rb:87:in `scoped'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/collection_association.rb:569:in `first_or_last'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/collection_association.rb:101:in `first'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.2.2/lib/active_record/associations/collection_proxy.rb:46:in `first'
    from (irb):14
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.2.2/lib/rails/commands/console.rb:47:in `start'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.2.2/lib/rails/commands/console.rb:8:in `start'
    from /<USER_PATH>/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.2.2/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

在我的分类模型中,我有:

class Category < ActiveRecord::Base
  has_many :article_relationships,:class_name  => 'Category::Article::ArticleRelationship',:foreign_key => 'category_id'

  has_many :articles,:through     => :article_relationships,:source      => :article
end

在我的Category :: Article :: ArticleRelationship中我有:

class Category::Article::ArticleRelationship < ActiveRecord::Base
  belongs_to :article,:class_name    => 'Article',:foreign_key   => 'article_id'
end

如何解决与Object相关的问题不支持#inspect?

注意:在相同的Category模型中,我有类似于Category :: Article :: ArticleRelationship的声明(它通过Category :: UserRelationship类与User类相关)并且它不会导致问题.

解决方法

您的应用程序上有两个名为Article的常量.一个是你的活跃记录类,顶级常量.另一个是模块
类别::文章.

当你执行belongs_to:article时,看起来rails开始在类中调用一个Article常量来调用belongs_to,因此它找到了错误的一个.这会导致各种混乱,因为您显然无法交替使用activerecord类和模块

设置:class_name => ‘:: Article’强制查找顶级Article类.

猜你在找的Ruby相关文章