Jimmy Bourassa
2014-Jul-16 21:48 UTC
Should Associations::Preloader allow subclasses not to define the association?
Hi,
I am working a project where subclasses (using STI) of an model have
different relationships. Quick Example:
class Course < ActiveRecord::Base
has_many :learning_units, as: :container
end
class LearningUnit <ActiveRecord::Base
end
class LessonGroup < LearningUnit
belongs_to :container, polymorphic: true
has_many :lessons,
-> { where(container_type: LessonGroup.name) },
class_name: "Lesson",
foreign_key: "container_id"
end
class Lesson < LearningUnit
belongs_to :container, polymorphic: true
# notice no lessons relationship
end
Everything works as expected except that when I try to do
course_instance.learning_units.includes(:lessons)
an exception is raised because one of the subclasses does not have a
`lessons` relationship.
This is where it happens:
https://github.com/rails/rails/blob/4-1-stable/activerecord/lib/active_record/associations/preloader.rb#L147
Unless I am mistaken, there's no configuration to change this behaviour. A
possible fix would be to raise the exception only if none of the classes
define the requested associations. Is there any chance such a change gets
merged?
Any thoughts are more than welcome.
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to rubyonrails-core+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.