我正在构建一个简单的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
帮助!提前感谢您的智慧!
答案 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"