如何向 Rails 多态关联添加方法?

发布于 2024-09-25 15:31:02 字数 260 浏览 2 评论 0原文

那么,如果我的应用程序中存在多态关联,是否有办法向其添加方法?例如,如果 :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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔戏命师 2024-10-02 15:31:02

我不知道如何使用模型来做到这一点,但是您可以轻松地使用 mixins 添加方法:

module RankableMethods
  def do_something_useful
    ...
  end
end

class Post < ActiveRecord::Base
  include RankableMethods
  belongs_to :rankable, :polymorphic = true
end

p = Post.new
p.respond_to?(:do_something_useful) # true

I don't know how you'd do this with a model, but you can easily add methods with mixins:

module RankableMethods
  def do_something_useful
    ...
  end
end

class Post < ActiveRecord::Base
  include RankableMethods
  belongs_to :rankable, :polymorphic = true
end

p = Post.new
p.respond_to?(:do_something_useful) # true
捶死心动 2024-10-02 15:31:02

您必须区分适用于 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文