8

I am creating association pretty much identical with the Rails Guides Patient-Appointment-Physician data model. A user has many prospects through prospect_subscription. However, when trying to access user.prospects in rails console, it throws the following error:

Rails couldn't find a valid model for Prospects association. Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass. (NameError)

uninitialized constant User::Prospects (NameError)

Which is strange because all three models are right there. Migration has been run and sample data has been populated and can be checked in pgAdmin. Why can't Rails find the model?

Association defined at the models are as follows:

models/prospect.rb

class Prospect < ApplicationRecord
  has_many :prospect_subscriptions
  has_many :users, through: :prospect_subscriptions
 end

models/user.rb


class User < ApplicationRecord
  has_many :prospect_subscriptions
  has_many :prospects, through: :prospect_subscriptions
end

models/prospect_subscription.rb
class ProspectSubscription < ApplicationRecord
  belongs_to :user
  belongs_to :prospect
end
Mike S
  • 151
  • 1
  • 8
  • 1
    Strange indeed. I can't see anything wrong with the assocations and it seems to be an odd inflection error since its looking for the constant `Prospects` instead of `Prospect`. Try running `"prospects".singularize.classify` which should return `"Prospect"` to see if that is the issue. – max Jan 10 '22 at 13:13
  • 1
    The only other thing I can think of is if you have a `type` column it could be acting as the STI inferance column. Seems unlikely though. The schema might be helpful here. – max Jan 10 '22 at 15:52
  • 1
    Thanks Max, after a long night, figured that wiping the database records clean and re-seeding helps. The difference is this time I assigned as `user.prospects << [prospect_name]`, to make sure that the joins are created in the backend. – Mike S Jan 11 '22 at 08:20
  • Thanks @MikeS for sharing the issue. I guessed that there should be some issue with database (even in migration). Please answer your own question with you insight. – Mostafa Ahangarha Jul 05 '22 at 12:21

1 Answers1

0

I figured that wiping the database records clean and re-seeding helps. The difference is this time I assigned as user.prospects << [prospect_name], to make sure that the joins are created in the backend.

Mike S
  • 151
  • 1
  • 8