ArgumentError:Rails 4中未定义的类/模块HABTM_Pubs

时间:2014-12-30 13:06:49

标签: ruby-on-rails serialization has-and-belongs-to-many

我正在建立一个系统来为酒吧生成酒吧测验。为确保酒吧不会两次收到相同的测验,酒吧和测验会有多对多的关联。

class Quiz < ActiveRecord::Base
  has_and_belongs_to_many :pubs
  serialize :rounds, Array
  before_create :generate_rounds

  def generate_rounds
    # Round class initializes with array of pubs
    NUMBER_OF_ROUNDS.times { rounds << Round.new(pubs: self.pubs) }
  end 
end

class Pub < ActiveRecord::Base
  has_and_belongs_to_many :quizzes
end

测验包含使用ActiveRecord方法serialize序列化的轮次(包含问题的Round对象数组)。

当我运行此代码时:

q = Quiz.new
q.pubs << Pub.create
q.save

我得到了:

ArgumentError: undefined class/module HABTM_Pubs

以前,我有一个belongs_to关系(属于一个酒吧的测验)并且没有发生此错误。

当我注释掉before_create回调(因此未创建轮次)时,q.save操作会成功。

来自我的schema.rb

create_table "pubs_quizzes", id: false, force: true do |t|
  t.integer "pub_id"
  t.integer "quiz_id"
end

Quiz.new.pubs这样的事情。

编辑:堆栈跟踪

from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/class_loader.rb:53:in `path2class'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/class_loader.rb:53:in `resolve'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/class_loader.rb:45:in `find'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/class_loader.rb:27:in `load'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:360:in `resolve_class'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:87:in `deserialize'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:122:in `visit_Psych_Nodes_Scalar'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/visitor.rb:15:in `visit'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/visitor.rb:5:in `accept'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:31:in `accept'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:302:in `block in revive_hash'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:300:in `each'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:300:in `each_slice'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:300:in `revive_hash'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/to_ruby.rb:161:in `visit_Psych_Nodes_Mapping'
from /home/geert/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/psych/visitors/visitor.rb:15:in `visit'

它必须与序列化有关。

相关项目? YAML::load raises undefined class/module error

1 个答案:

答案 0 :(得分:1)

使用引用ActiveRecord关联的对象序列化数组似乎会导致错误。

替换

Round.new(pubs: self.pubs)

Round.new(pub_ids: self.pubs.map { |pub| pub.id })

并在Round类中获取pub本身会使错误消失。