Rails如何为多态关联填充"model_type"字段?

Rob*_*bin 5 ruby-on-rails presenter polymorphic-associations ruby-on-rails-3

我有一个活动模型.它belongs_to :parent, :polymorphic => true.

是否Rails的使用parent.class.name,parent.model_name还是其他什么东西来填充PARENT_TYPE场?

我希望Presenter的行为与它包装的父对象相似,我需要覆盖正确的方法.

谢谢.

Sea*_*ill 6

我现在正在使用Rails 3.0.7,并且在active_record-3.0.7/lib/active_record/association.rb1773行中定义了多态类型.

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
Run Code Online (Sandbox Code Playgroud)

所以看起来它正在调用class_name.underscore然后附加"_type".对于rails 3.1,这可能略有不同,但这应该是一个很好的起点.

  • 并且`class_name`被定义为`@class_name || = options [:class_name] || derive_class_name`如果我没弄错的话.`derive_class_name`是`name.to_s.camelize`.所以我猜它只是调用Model.name.to_s.camelize,我应该覆盖`name`方法? (2认同)