Same class name in STI, with different namespaces
-
22-12-2019 - |
Question
I have something like this
class A < ActiveRecord::Base
# Parent class
end
class B < ActiveRecord::Base
# Parent class
end
# models/a/x.rb
class X < A
end
# models/b/x.rb
class X < B
end
# application.rb
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
I need to reference X::B, but still the X from the A's namespace gets referenced. Is there anyway to achieve this, or I just need to change my X's class name?
Thanks
Solution
File structure itself can't define namespace at all. You need to write the constant accordingly.
# models/a/x.rb
class A::X < A
# models/b/x.rb
class B::X < B
Also, in Rails 3 there is no need to define loading path of any files inside /app, not sure how Rails 4 works but I guess it should be similar. If so your last line is unnecessary as well.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow