Reputation: 33
I'm facing a strange issue with an ActiveRecord association in my Ruby on Rails project. When I try to access the laps
association method from my User
model, I get a peculiar error.
Error:
ArgumentError: The Lap model class for the User#laps association is not an ActiveRecord::Base subclass.
I've double-checked, and Lap
is definitely a subclass of ActiveRecord::Base
. I'm using Rails 7.1.3 and Ruby 3.2.2.
Here's the code for my User
model:
class User < ApplicationRecord
has_many :laps
end
And here's the code for my Lap
model:
class Lap < ApplicationRecord
belongs_to :user
end
I can't figure out why I'm getting this error. Has anyone else encountered a similar issue or have any ideas on how to resolve it?
I use
User.reflect_on_association(:laps).klass
what create an error
but with the relation quiz has_many :laps
and Quiz.reflect_on_association(:laps).klass
There is no errors in the 2nd case so I didn't understand why to similar code have different résult.
Upvotes: 2
Views: 544
Reputation: 5314
A more straightforward fix for this is to tell it what the model class is and make the namespacing clear.
class User < ApplicationRecord
has_many :laps, class_name: "::Lap"
end
The ::
at the front tells Rails that should not be looking for User::Lap
but just Lap
.
Upvotes: 0
Reputation: 11
I do not have enough information here but I think you probably have app/models/lap.rb
in and app/models/user/lap.rb
If that's the case, then there's probably a naming collision at play. You need to change the name lap.rb in the module to something else eg. app/models/user/lappable.rb
module User::Lappable
extend ActiveSupport::Concern
end
class User
include Lappable
end
Upvotes: 0