reflect_on_association can be mistakenly nil for inherited classes
denzelem opened this issue · 3 comments
denzelem commented
rails g migration createFoos
rails g migration createBars
Working example:
Bar = Class.new(ApplicationRecord)
class Foo < ApplicationRecord
belongs_to :bar
Foo::Child # after association is no problem
end
class Foo::Child < Foo
assignable_values_for :bar do
[]
end
end
Foo::Child.reflect_on_association(:bar) # =>
<ActiveRecord::Reflection::BelongsToReflection:0x00000004dc4e58 ... >
Broken example:
Bar = Class.new(ApplicationRecord)
class Foo < ApplicationRecord
Foo::Child # this will cause Foo::Child to not have the correct reflect_on_association for bar
belongs_to :bar
end
class Foo::Child < Foo
assignable_values_for :bar do
[]
end
end
Foo::Child.reflect_on_association(:bar) # => nil
This only happens if the child class is loaded in the parent class before the association evaluation (here belongs_to
).
Maybe we can super reflect_on_association
if it is nil
.
triskweline commented
@denzelem Why did you need to refer to Foo::Child
inside the class definition of Foo
?
denzelem commented
@triskweline It was a trait, which took a class as argument. Something like
class Foo < ApplicationRecord
include DoesTakeSnapshots[
as: Foo::Child
]
belongs_to :bar
end
triskweline commented
I'm assuming this is a limitation of ActiveRecord, which probably copies association definitions at inheritance. It's probably also the reason why when you use has_many
, the :class_name
option takes a string, not a class. This would also be a workaround for the code sample above.
I'm considering this to be out of scope for this gem, sorry.