I'm trying to build a seeds.rb file to add an initial admin user to the database. I have a Users table and model, and a Roles table and model. I have a join table, roles_users to join the users role and permissions. Here's the schema:
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
I've figured out how to add the Users and the Roles using the repsective models for each:
#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 => "[email protected]", :password => "admin")
How do I add the join to make grant the admin super_admin privileges (database being used is sqlite3)?
Assuming you have defined a has_and_belongs_to_many association in your User model:
has_and_belongs_to_many :roles, :join_table => "roles_users"
In your seeds.rb file, you can then add roles to a user as shown below (this example adds ALL roles to the user):
u = User.create(:first_name => "admin", :email => "[email protected]", :password => "admin")
Role.all.each { |role| u.roles << role }
To grant the user only the 'super_admin' role, you could do something like this:
u = User.create(:first_name => "admin", :email => "[email protected]", :password => "admin")
u.roles << Role.find_by_name("super_admin")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With