如何向 Rails 多态关联添加方法?
那么,如果我的应用程序中存在多态关联,是否有办法向其添加方法?例如,如果 :post、:photo 和 :user 都与具有名为 :rankable 的多态关联的 :rankings 相关联,我可以以某种方式在 :rankable 上创建方法,然后由 :post、:photo 或 :user 继承吗?我的猜测是,如果可能的话,需要我向应用程序添加一个 Rankable 模型并在其中定义方法。这可能吗?如果是这样,并且我需要创建一个模型是正确的,那么该模型将从哪个类继承,或者我将如何将其定义为多态关系?
So, if I have a polymorphic association throughout my application, is there a way to add methods to it? For instance, if :post, :photo and :user are all associated to :rankings with a polymorphic association named :rankable, can I somehow create methods on :rankable that would then be inherited by :post, :photo or :user? My guess is that, if it is possible, it would require me adding a Rankable model to the app and defining methods within it. Is that possible? If so, and I am correct in needing to create a model, what class would that model inherit from or how would I define it as being that polymorphic relationship?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道如何使用模型来做到这一点,但是您可以轻松地使用 mixins 添加方法:
I don't know how you'd do this with a model, but you can easily add methods with mixins:
您必须区分适用于 ActiveRecord 多态关联的“多态”概念和经典 OOP 继承意义上的“多态”概念。
第一种意义上的“Rankable”多态类型并不存在,除非作为 ActiveRecord 中的数据库约定,允许一个表中的记录引用多个可能的其他表中的记录。如果您想在对象模型中更具体地表达这种抽象(第二种意义上的多态性),您必须声明一个单独的类或模块,您的“Rankable”ActiveRecords 可以混合其中或从中继承。
You have to separate the concepts of 'polymorphic' as it applies to an ActiveRecord polymorphic association, and 'polymorphic' in the classic OOP sense of inheritance.
A 'Rankable' polymorphic type in the first sense doesn't exist except as a database convention within ActiveRecord that lets a record in one table refer to records in multiple possible other tables. If you want to express this abstraction more specifically in your object model -- polymorphism in the second sense -- you'll have to declare a separate Class or Module that your 'Rankable' ActiveRecords can mix in or inherit from.