我想設置一個基本的用戶身份驗證 - 我有用戶登錄的東西排序,並且需要爲用戶添加角色。ruby on rails rake db:種子未定義的方法
基本上我想我的用戶有很多角色,這使他們能夠訪問權限。
我寫了一些種子數據,但不斷收到錯誤:
rake aborted!
undefined method `roles' for #<Array:0x007f8c0581ba80>
我的種子數據是這樣的:
#user
user = User.create!([{ email: '[email protected]', first_name: 'Admin', last_name: 'Test', password: 'admin', password_confirmation: 'admin'}])
user.roles << admins = Role.create!(:name => "Admin")
#user roles
create = Right.create!(:resource => "users", :operation => "CREATE")
read = Right.create!(:resource => "users", :operation => "READ")
update = Right.create!(:resource => "users", :operation => "UPDATE")
delete = Right.create!(:resource => "users", :operation => "DELETE")
#add the roles to the admin
admins.rights << read
admins.rights << create
admins.rights << update
admins.rights << delete
耙分貝:遷移工作正常,所有表列是因爲我希望他們至。正當我運行rake db:seed時,它會中止上述錯誤。我明白錯誤在說什麼 - 我只是不知道我在哪裏定義has_many角色。
我已經經歷了模型非常密切,但似乎無法找到我錯過了什麼。
和我的模型文件看起來是這樣的:
class User < ActiveRecord::Base
has_secure_password
has_many :assignments
has_many :roles, :through => :assignments
attr_accessible :email, :first_name, :last_name, :password, :password_confirmation
validates_presence_of :email, :on => :create
validates :password, :confirmation => true
validates :password_confirmation, :presence => true
validates_uniqueness_of :email
#will be using this later to check if the user has access to resources/actions
# def can?(action, resource)
# roles.includes(:rights).for(action, resource).any?
# end
end
class Role < ActiveRecord::Base
has_many :grants
has_many :assignments
has_many :users, :through => :assignments
has_many :rights, :through => :grants
scope :for, lambda{|action, resource|
where("rights.operation = ? AND rights.resource = ?",
Right::OPERATION_MAPPINGS[action], resource
)
}
end
class Right < ActiveRecord::Base
attr_accessible :operation, :resource
has_many :grants
has_many :roles, :through => :grants
OPERATION_MAPPINGS = {
"new" => "CREATE",
"create" => "CREATE",
"edit" => "UPDATE",
"update" => "UPDATE",
"destroy" => "DELETE",
"show" => "READ",
"index" => "READ"
}
end
class Grant < ActiveRecord::Base
attr_accessible :right_id, :role_id
belongs_to :role
belongs_to :right
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
attr_accessible :role_id, :user_id
end
任何幫助,將不勝感激。
非常感謝你非常:) –