[英]NameError (uninitialized constant ApplicationRecord) in has_many through association
I am creating users and assigning roles using has_many :through
association, as per the naming convention. 我根据命名约定使用has_many :through
关联创建用户并分配角色。 If I am wrong or any improvements could be made, please feel free to guide me 如果我错了或可以做出任何改进,请随时指导我
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
I created association using following command 我使用以下命令创建了关联
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
When i run console with following: 当我使用以下命令运行控制台时:
r1=Role.create(name:"admin",active:true)
r2=Role.create(name:"player",active:true)
u1 = User.create(first_name:"alex", roles: [r1,r2])
I am getting following error: 我收到以下错误:
Traceback (most recent call last):
2: from (irb):3
1: from app/models/user_role.rb:1:in `<main>' NameError (uninitialized constant ApplicationRecord)
I am a beginner in rails, please help me with proper guidance 我是Rails的初学者,请在正确的指导下帮助我
Looks like you do not have an ApplicationRecord
model (you do not have to be on Rails 5+ to do that, actually it's a good idea to adopt this prior to update): 看起来您没有ApplicationRecord
模型(不必在Rails 5+上执行此操作,实际上,在更新之前采用此方法是一个好主意):
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
You should do that like this: 您应该这样:
u1 = User.create(first_name:"alex")
u1.roles.create([{name:"admin",active:true}, {name:"player",active:true}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.