This one really has me scratching my head. I'm working with polymorphic relations relating to multiple classes that all inherit from one abstract class. This is working well, but I'm running into an error when I try and access the associated object from the polymorphic relations. Here's my implementation:
class Foo < ApplicationRecord
belongs_to :options, polymorphic: true
accepts_nested_attributes_for :options
def build_options(params)
self.options = options_type.constantize.new(params)
end
end
module Mod
class Option < ApplicationRecord
self.abstract_class = true
has_one :foo, as: :options
self.table_name_prefix
'foo_'
end
end
class Bar < Options
end
class Baz < Options
end
end
This has been working well so far, but I'm now running into an issue when I try something like this:
Bar.first.foo
I get this error:
ActiveRecord::AssociationNotFoundError (Association named 'foo' was not found on Foo::Bar; perhaps you misspelled it?)
The thing that makes this weird to me is that if I call Bar.first.methods
, I get :foo
as an option.
Any idea what I need to do to fix this and still use the Options
class inheritance? I know that I can just define the has_one
on the subclasses, but it applies to all the children of Options
and if I can keep the association there, I would like to.
Edit: The plot thickens! After playing around for a bit, I have now realized that SOME of the child classes have the association working, but some don't. I also can't seem to find any difference between the classes that are working vs. the ones that aren't.