我正在尝试构建一个seeds.rb文件,以便将初始管理员用户添加到数据库中。我有一个Users表和模型,以及一个Roles表和模型。我有一个连接表,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
我已经找到了如何使用每个的repsective模型添加用户和角色:
#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")
如何添加联接以使grant具有admin super_admin权限(正在使用的数据库是sqlite3)?
答案 0 :(得分:3)
假设您在用户模型中定义了has_and_belongs_to_many关联:
has_and_belongs_to_many :roles, :join_table => "roles_users"
在seeds.rb文件中,您可以向用户添加角色,如下所示(此示例将所有角色添加到用户):
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")
答案 1 :(得分:0)
通常我将对象保存到某个变量中:
#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
或者你可以在将它们推入关联数组时创建它们,因此不需要传递这么多变量。