How do you add JOIN information to rails seeds.rb?

I am trying to create a seeds.rb file to add the initial admin user to the database. I have a table and user model, a table and role model. I have a connection table, role_users, to join the user role and permissions. Here's the diagram:

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 figured out how to add users and roles using reps 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 => " admin@domain.com ", :password => "admin") 

How to add a connection to provide super_admin administrator privileges (using sqlite3 database)?

+6
source share
2 answers

Assuming you defined the has_and_belongs_to_many association in your user model:

 has_and_belongs_to_many :roles, :join_table => "roles_users" 

In the seeds.rb file, you can add roles to the user, as shown below (in this example, all roles are added to the user):

 u = User.create(:first_name => "admin", :email => " admin@domain.com ", :password => "admin") Role.all.each { |role| u.roles << role } 

To give the user only the super_admin role, you can do something like this:

 u = User.create(:first_name => "admin", :email => " admin@domain.com ", :password => "admin") u.roles << Role.find_by_name("super_admin") 
+3
source

I usually save objects in some variable:

 #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") 

whereas I just paste them into an associative array:

 admin.roles << supr << schl << schs johny.roles << stut 

Or you can just create them when you push them into an associative array, so you wouldn't need to pass so many variables.

0
source

Source: https://habr.com/ru/post/887074/


All Articles