ruby on rails - mismatch setting and preloading of polymorphic association for STI models -
let see have polymorphic table
class db::document < activerecord::base # documentable_type, documentable_id belongs_to :documentable, polymorphic: true end class db::ticket < activerecord::base has_one :document, as: :documentable def self.find_sti_class(type_name) activesupport::dependencies.constantize("db::ticket::#{sti_type_for(type_name)}") end self.inheritance_column = :type self.store_full_sti_class = false def self.sti_name self.to_s.split('::').last end end class db::ticket::train < db::ticket end class ticket::airplain < db::ticket end
when set association:
doc = document.new doc.documentable = db::ticket::train.first! # docuementable_type 'db::ticket'
when preload polymorphic association:
db::ticket.where(id: [1,2]).preload(:document).to_a # select * documents documentable_id in (1,2) , documentable_type = 'ticket'
i think because on association.writer uses name
of base_class
module activerecord # = active record belongs polymorphic association module associations class belongstopolymorphicassociation < belongstoassociation #:nodoc: ... def replace_keys(record) super owner[reflection.foreign_type] = record.class.base_class.name end ... end end end
and on preloading uses sti_name
of base_class
module activerecord module associations class preloader class association #:nodoc: ... def build_scope scope = klass.unscoped ... if options[:as] scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name }) end ... end ... end end end end
why sql preload generates wrong documentable_type? mistake in using of sti/polymorhic or activerecord bug?
Comments
Post a Comment