2011-05-01 113 views
6

我正在嘗試構建一個seeds.rb文件來將一個初始管理用戶添加到數據庫。我有一個用戶表和模型,以及一個角色表和模型。我有一個連接表,roles_users來加入用戶角色和權限。這裏的架構:如何將JOIN信息添加到rails seeds.rb文件中?

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 => "[email protected]", :password => "admin") 

我如何添加一個連接,使授予管理員超級管理員特權(正在使用的數據庫是sqlite3)?

回答

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 => "[email protected]", :password => "admin") 
Role.all.each { |role| u.roles << role } 

要授予用戶只有 '超級管理員' 的角色,你可以做這樣的事情:

u = User.create(:first_name => "admin", :email => "[email protected]", :password => "admin") 
u.roles << Role.find_by_name("super_admin") 
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 

或者,你可以創建它們,當你推入聯想數組,所以不需要傳遞這麼多的變量。