Home > Net >  uninitialized constant error when trying to include class/object association
uninitialized constant error when trying to include class/object association

Time:04-12

I have been trying to pass an User object to a variable and include its UserSettings relative object using the includes method:

logged_user = User.includes(:user_settings).find_by(login: login)

But I keep getting the following error:

"error": "uninitialized constant User::UserSettings"

Here are the classes' definitions:

class UserSetting < ApplicationRecord
  belongs_to :user
end 

class User < ApplicationRecord

  has_one :user_settings, :class_name => 'UserSettings'
  has_many :sessions

  scope :active, -> { where(active: true) }

end

What am I doing wrong?

CodePudding user response:

In

has_one :user_settings, :class_name => 'UserSettings'

try to change association plural user_settings to user_setting and you can remove class_name or remove plural UserSettings to singularly UserSetting, it will be like this:

has_one :user_setting, :class_name => 'UserSetting'

then change in includes user_settings to user_setting

logged_user = User.includes(:user_setting).find_by(login: login)

I hope this works for you.

  • Related