How does Rails populate the “model_type” field for polymorphic associations?

扶醉桌前 提交于 2019-12-23 12:09:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8350037/how-does-rails-populate-the-model-type-field-for-polymorphic-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!