Vijay
Vijay

Reputation: 5

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. 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

Upvotes: 0

Views: 291

Answers (2)

Abolfazl Mahmoodi
Abolfazl Mahmoodi

Reputation: 390

You should do that like this:

u1 = User.create(first_name:"alex")
u1.roles.create([{name:"admin",active:true}, {name:"player",active:true}])

Upvotes: -1

Vasfed
Vasfed

Reputation: 18444

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):

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

Upvotes: 2

Related Questions