Search code examples
ruby-on-railseventsnameerrormodel-associationsuninitialized-constant

Rails NameError 'uninitialized constand User::Events' using devise


I feel like the title could be more specific but I'm having a hard time understanding the issue, and I'm unsure of what the problem is so I apologize.

I have Users, created with devise, users can make events, and the events have many users associated with them as attendees.

My user model:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :validatable

  has_many :created_events, foreign_key: :owner_id, class_name: "Events"
  has_many :attendees, through: :attendees

end

My event model

class Event < ApplicationRecord
  belongs_to :owner, class_name: 'User'
  has_many :attendees, through: :attendees
end

My attendee model, to join the two

class Attendee < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :attended_event, class_name: "Event"
end

I get the "uninitialized constant User::Events" error when trying to use something like this, going to /users/[:id], in my users_controller file:

class UsersController < ApplicationController

  before_action :authenticate_user!

  def show
    @user = User.find(params[:id])
    @created_events = @user.created_events.all
  end

end

or when doing a new > create action in the events_controller file:

def new
  @event = Event.new
end

def create
  @event = current_user.created_events.build(event_params)

    respond_to do |format|
      if @event.save
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
        format.json { render :show, status: :created, location: @event }
      else
        format.html { render :new }
        format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

It worked fine until I added the join model, and now I'm getting the error:

uninitialized constant User::Events

Thanks in advance. I'm having a really hard time with this.


Solution

  • Simple typo:

    has_many :created_events, foreign_key: :owner_id, class_name: "Events"
    

    should be class_name: 'Event'