ruby-on-rails - 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
解决方案
你可以使用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
推荐阅读
- azure - 当 Azure 区域出现故障时,Application Insight 会发生什么。应用程序洞察力是否仍可访问
- c# - CefSharp 中的 Google 日历
- android - 如何在占位符中创建一个小加载微调器(Glide)
- r - Shinymeta:如何在模块中使用 expandChain?
- reactjs - useCallback 和 useMemo 有什么区别
- c# - 在检查器中获取当前按下的键
- c# - 如何将 Saxon XdmNode 转换为 XmlDocument?
- python - Keras CNN 用于图像转换、NAN 损失
- c - ESP32-CAM 掉帧
- android - 如何使用 Firestore 数据库和 Firebase 身份验证创建登录方法