【问题标题】:How does Rails populate the "model_type" field for polymorphic associations?Rails 如何为多态关联填充“model_type”字段?
【发布时间】:2012-01-11 02:39:57
【问题描述】:

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

Rails 是否使用 parent.class.nameparent.model_name 或其他东西来填充 parent_type 字段?

我希望 Presenter 表现得像它包装的父对象,我需要重写正确的方法。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 polymorphic-associations presenter


    【解决方案1】:

    我现在正在使用 Rails 3.0.7,多态类型在 active_record-3.0.7/lib/active_record/association.rb 的第 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
    

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

    【讨论】:

    • 如果我没记错的话,class_name 被定义为@class_name ||= options[:class_name] || derive_class_namederive_class_namename.to_s.camelize。所以我猜它只是调用Model.name.to_s.camelize,我应该重写name方法?
    • Pfff... 实际上它在控制台中从头开始工作正常,只是代码中的其他地方,有人以错误的方式创建了对象,“显式”传递 :parent_type...
    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多