根据命名约定,我正在使用has_many :through
关联来创建用户并分配角色。如果我错了或可以做出任何改进,请随时指导我
create_table "roles", force: :cascade do |t|
t.string "name"
t.boolean "active"
t.integer "counter"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "photo"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
我使用以下命令创建了关联
rails g model UserRole role:references user:references
create_table "user_roles", force: :cascade do |t|
t.integer "role_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["role_id"], name: "index_user_roles_on_role_id"
t.index ["user_id"], name: "index_user_roles_on_user_id"
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, through: :user_roles
end
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
end
class UserRole < ApplicationRecord
belongs_to :user
belongs_to :role
end
当我使用以下命令运行控制台时:
r1=Role.create(name:"admin",active:true)
r2=Role.create(name:"player",active:true)
u1 = User.create(first_name:"alex", roles: [r1,r2])
我遇到以下错误:
Traceback (most recent call last):
2: from (irb):3
1: from app/models/user_role.rb:1:in `<main>' NameError (uninitialized constant ApplicationRecord)
我是Rails的初学者,请在正确的指导下帮助我
答案 0 :(得分:2)
看起来您没有ApplicationRecord
模型(您不必使用Rails 5+即可,实际上,在更新之前采用此模型是一个好主意):
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
答案 1 :(得分:-1)
您应该这样做:
u1 = User.create(first_name:"alex")
u1.roles.create([{name:"admin",active:true}, {name:"player",active:true}])