首页 > 解决方案 > Rails 子对象使用父方法而不是它自己的方法

问题描述

我有Vibe::Interaction::SurveyMessage继承自的 Child 类Interaction。它们共享同一个表,并且由SurveyMessage标识{app: :vibe, kind:"survey"}

控制器通过父类调用方法: Interaction.find(param[:id]).refresh

问题是即使对象是 a SurveyMessage Object,它也使用父级的update_message方法(空的)。

有没有办法强制对象作为SurveyMessage Object父类(Interaction)的实例化它?或者有没有办法通过父类来识别对象是否属于子类?

class Interaction < ApplicationRecord
  enum app: [ :praise, :review, :vibe, :atlas, :goals ]
  belongs_to :survey, class_name: 'Survey', foreign_key: :vibe_survey_id, required: false
  serialize :attachments 

  def message
    {
      text: self.text,
      attachments: self.attachments
    }
  end

  def update_message
  end

  def refresh(options = {})
    update_message
    h = self.history << {
            :type => :refresh,
            :timestamp => Time.current.to_s
          }
    update( 
      history: h 
    )
    # Submit code
    message
  end

end
class Vibe::Interaction::SurveyMessage < Interaction
  default_scope -> { where(app: :vibe, kind: "survey") }

  def update_message
    msg = survey.answer(user_id, self, additional_options||{} )
    update( text: msg[:text], attachments: msg[:attachments])
  end

end

标签: ruby-on-railsinheritanceactiverecordruby-on-rails-5

解决方案


你可以使用becomes方法

https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes

如果您的子类有模式

i = Interaction.find_by(id: id)
i = i.becomes("#{i.kind.capitalize}Message".constantize) if i&.vibe? # or in parent class as a method #downcast
i.refresh

推荐阅读