首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails子对象使用父方法而不是它自己的方法

Rails子对象使用父方法而不是它自己的方法
EN

Stack Overflow用户
提问于 2020-01-16 22:25:23
回答 2查看 470关注 0票数 0

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

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

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

是否有一种方法强制对象充当一个SurveyMessage Object,用父类(Interaction)实例化它?或者是否有一种通过父类标识对象是否属于子类的方法?

代码语言:javascript
复制
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
代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-17 20:48:56

您可以使用becomes方法

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

如果您的子类有一个模式

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2020-01-17 16:43:09

我设法解决了它,在父Interaction上创建了一个路由器方法:

代码语言:javascript
复制
  def self.find_child(id)
    i = Interaction.find_by(id: id)
    if i&.vibe? and i.kind=="survey"
      ans = Vibe::Interaction::SurveyMessage.find(id)
    elsif i&.vibe? and i.kind=="partial"
      ans = Vibe::Interaction::PartialMessage.find(id)
    elsif (etc)
      ...
    else
      ans = i
    end
    ans
  end

虽然不雅致,但效果很好。如果有人有更好的解决方案我很想听。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59778717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档