未定义的方法`角色'?

时间:2011-12-17 19:17:09

标签: ruby-on-rails ruby ruby-on-rails-3 cancan

我在使用我的用户的默认角色播种数据库时出现问题。

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  validates_presence_of :username, :email, :password, :password_confirmation
  validates_uniqueness_of :username, :email

  before_create :setup_default_role_for_new_users

  ROLES = %w[admin default]

  private

  def setup_default_role_for_new_users
    self.roles = [ "default" ]
  end
end

Seeds.rb

puts 'Loading seed data now....'
user1 = User.create(:username => 'admin',   :email => 'testing@email.com', :password => 'qweasd',:password_confirmation => 'qweasd', :role => 'admin')
user2 = User.create(:username => 'userone', :email => 'user1@email.com', :password => 'qweasd', :password_confirmation => 'qweasd')
user3 = User.create(:username => 'usertwo', :email => 'user2@email.com', :password => 'qweasd',:password_confirmation => 'qweasd')
puts 'Users added'

播种错误时,我得到:

undefined method `roles' for #<User:0x53f4c60>

我的数据库中有role列,为什么它不起作用?

2 个答案:

答案 0 :(得分:1)

如果您希望能够像以下那样批量分配attr_accessible,请添加:角色:

user1 = User.create(:username => 'admin',   :email => 'testing@email.com', :password => 'qweasd',:password_confirmation => 'qweasd', :role => 'admin')

也是:role还是:roles?如果您有:role:roles粘贴schema.db,请检查您的数据库。

答案 1 :(得分:1)

因为您使用

before_create :setup_default_role_for_new_users. 

首先将user1设置为admin(在内存中),然后将before_create设置为默认值

这样的事情应该这样做

before_create :setup_default_role_for_new_users, :if => :not_user1


def not_user1
  username != "admin"
end