为什么我得到一个"未初始化的常数"错误?

时间:2013-06-19 05:16:47

标签: ruby-on-rails ruby-on-rails-3 constants rails-activerecord

我有以下代码:

class Zombie < ActiveRecord::Base
  attr_accessible  :name, :rotting, :age
  has_many :assignments
  has_many :roles, through: :assignments
end

class Role < ActiveRecord::Base
  attr_accessible :title
  has_many :assignments
  has_many :zombies, through: :assignments
end

class Assignments < ActiveRecord::Base
  attr_accessible :role_id, :zombie_id
  belongs_to :zombie
  belongs_to :role
end

在控制台中,当我尝试运行此代码时:

zombie = Zombie.first
role = Role.first
zombie.assignments.create(role: role)

我收到以下错误:

NameError: uninitialized constant Zombie::Assignment.

我在这里犯了什么错误吗?

2 个答案:

答案 0 :(得分:4)

Rails模型是单数形式,因此将类名Assignments更改为Assignment

答案 1 :(得分:0)

尝试在控制台上运行以下代码

zombie = Zombie.first
zombie.roles << Role.find_by_title("Title")
zombie.roles