How does Rails populate the "model_type" field for polymorphic associations?
Asked Answered
F

1

5

I have an Activity model. It belongs_to :parent, :polymorphic => true.

Does Rails use parent.class.name, parent.model_name or something else to populate the parent_type field?

I want a Presenter to behave like the parent object it wraps, and I need to override the right method.

Thanks.

Flutist answered 1/12, 2011 at 23:51 Comment(0)
P
6

I'm working with Rails 3.0.7 right now, and the polymorphic type is being defined in active_record-3.0.7/lib/active_record/association.rb, line 1773.

def create_belongs_to_reflection(association_id, options)
  options.assert_valid_keys(valid_keys_for_belongs_to_association)
  reflection = create_reflection(:belongs_to, association_id, options, self)

  if options[:polymorphic]
    reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
  end

  reflection
end

So it looks like it is calling class_name.underscore and then appending "_type". This may be slightly different for rails 3.1, but this should be a good starting place.

Physiological answered 2/12, 2011 at 0:0 Comment(2)
And class_name is defined as @class_name ||= options[:class_name] || derive_class_name if I'm not mistaken. derive_class_name is name.to_s.camelize. So I guess its just calling Model.name.to_s.camelize, and I should override the name method?Flutist
Pfff... actually it was working fine from scratch in the console, it's just that somewhere else in the code, someone created the object the wrong way, passing "explicitly" the :parent_type...Flutist

© 2022 - 2024 — McMap. All rights reserved.