2

我有以下代碼:爲什麼我會收到「未初始化的常量」錯誤?

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. 

難道我在這裏犯了什麼錯誤?

回答

0

嘗試在您的控制檯上運行下面的代碼

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

該解決方案使其工作,但不解決問題。 Rails模型是單數的,考慮將'Assignments'改爲'Assignment' –

4

Rails模型是單數,因此將類名稱Assignments更改爲Assignment

+0

現在我得到這個錯誤::加載ActiveModel :: MassAssignmentSecurity錯誤:無法大規模指派保護的屬性:角色 –

+1

只有attr_accessible屬性是質量分配。在你的情況下,角色沒有在attr_accessible中定義。更好地使用'zombie.assignments.create(role_id:role)',當rails定義** has_many時,rails還創建role_id和zombie_id attr_accessible。**因此'attr_accessible:role_id,:zombie_id'是不必要的。 – Tukuna

相關問題