我正在尝试建立一个种子。将初始admin用户添加到数据库。我有一个用户表和模型,以及一个角色表和模型。我有一个连接表,roles_users来连接用户的角色和权限。模式如下:
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles_users", :id => false, :force => true do |t|
t.integer "role_id"
t.integer "user_id"
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "reset_password_token"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "first_name"
t.string "last_name"
end
我已经知道如何使用各自的模型添加用户和角色:
#Setup our default roles
Role.create(:name => "super_admin")
Role.create(:name => "school_leader")
Role.create(:name => "school_staff")
Role.create(:name => "student")
#Setup and initial super admin user
User.create(:first_name => "admin", :email => "admin@domain.com", :password => "admin")
我如何添加连接,使授予管理员super_admin特权(使用的数据库是sqlite3)?
假设您已经在用户模型中定义了一个has_and_belongs_to_many关联:
has_and_belongs_to_many :roles, :join_table => "roles_users"
在你的种子。然后,您可以向用户添加角色,如下所示(本例向用户添加所有角色):
u = User.create(:first_name => "admin", :email => "admin@domain.com", :password => "admin")
Role.all.each { |role| u.roles << role }
要只授予用户'super_admin'角色,您可以这样做:
u = User.create(:first_name => "admin", :email => "admin@domain.com", :password => "admin")
u.roles << Role.find_by_name("super_admin")
通常我将对象保存到某个变量中:
#Setup our default roles
supr = Role.create(:name => "super_admin")
schl = Role.create(:name => "school_leader")
schs = Role.create(:name => "school_staff")
stut = Role.create(:name => "student")
#Setup and initial super admin user
admin = User.create(:first_name => "admin")
johny = User.create(:first_name => "johny tables")
然后我把它们放入关联数组中:
admin.roles << supr << schl << schs
johny.roles << stut
或者您可以在将它们压入关联数组时创建它们,因此不需要传递那么多变量。