抽象类和子类的最佳ActiveRecord继承策略
试图找出解决这个特定问题的最佳 ActiveRecord 继承策略:
我有一个抽象类,我们将其称为 Message
,具有以下方法/属性。
Message
|- recipient
|- sender
\ body
我有两个子类,
ColorMessage < Message
|- first_color
|- second_color
\ body (returns "#{sender.name} says #{first_color} > #{second_color}")
WeatherMessage < Message
|- current_weather_adverb
\ body (returns "#{sender.name} enjoys #{current_weather_adverb} weather")
我希望能够对所有 Message
运行查询并显示它们的主体,而不必担心它们的具体类型。基本上将 Message
视为一个接口。
我熟悉 STI,在这种情况下这是正确的解决方案吗?
感谢您的帮助!
trying to figure out the best ActiveRecord inheritance strategy for this particular problem:
I have an abstract class, let's call it Message
with the following methods/attributes.
Message
|- recipient
|- sender
\ body
And I have two sub classes
ColorMessage < Message
|- first_color
|- second_color
\ body (returns "#{sender.name} says #{first_color} > #{second_color}")
WeatherMessage < Message
|- current_weather_adverb
\ body (returns "#{sender.name} enjoys #{current_weather_adverb} weather")
I'd like to be able to run a query for all Message
s and display their bodies without having to worry about their concrete types. Basically treating Message
as an interface.
I am familiar with STI, is that the correct solution in this case?
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这适合单表继承(STI(。
您可以请求 Message.all 或 ColorMessage.all,rails 将为您处理对象转换。
I consider this an appropriate use for single-table-inheritance (STI(.
You can ask for Message.all or ColorMessage.all and rails will take care of the object casting for you.