NameError:访问一对多关联时未初始化的常量

时间:2014-10-15 18:58:34

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我正在构建一个简单的RoR 4益智游戏,它具有简单的一对多关联......

class Puzzle < ActiveRecord::Base
  belongs_to :author, class_name: :user
end

class User < ActiveRecord::Base
  has_many :authored_puzzles, foreign_key: :author_id, class_name: :puzzle
end

class AddAuthorIdToPuzzle < ActiveRecord::Migration
  def change
    add_reference :puzzles, :author_id, index: true
  end
end

从拼图方面访问时工作正常......

> p Puzzle.first.author
  Puzzle Load (1.1ms)  SELECT  "puzzles".* FROM "puzzles"   ORDER BY "puzzles"."id" ASC LIMIT 1
=> nil

但是从用户端访问时崩溃...

> p User.first.authored_puzzles
  User Load (1.0ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
NameError: uninitialized constant User::puzzle

帮助!提前感谢您的智慧!

1 个答案:

答案 0 :(得分:2)

问题在于:

class User < ActiveRecord::Base
  has_many :authored_puzzles, foreign_key: :author_id, class_name: :puzzle
end

没有名为puzzle的班级。类名是Puzzle,所以你想要这个:

has_many :authored_puzzles, foreign_key: :author_id, class_name: "Puzzle"