has_many :through association cannot find a valid model
Asked Answered
U

2

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
Undertook answered 10/1, 2022 at 9:25 Comment(4)
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.Kristynkrock
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.Kristynkrock
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.Undertook
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.Buenabuenaventura
U
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.

Undertook answered 25/11, 2022 at 3:20 Comment(0)
T
0

I got this error due to a typo that I had added in the association object. In this example, it would be the User object.

I had added something like:

afteR_create :foo

Fixing that removed the issue listed above

Tailband answered 15/3 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.