代码之家  ›  专栏  ›  技术社区  ›  Dex

关于关系的Rails问题(中间)

  •  0
  • Dex  · 技术社区  · 14 年前

    我将此解决方案作为多态性的替代方案来实现。

    Why can you not have a foreign key in a polymorphic association?

    但我想知道是否有一个简单的方法:

    Article.comments 而不是 Article.commentable.comments

    1 回复  |  直到 7 年前
        1
  •  3
  •   Peter Brown    14 年前

    你应该可以使用 delegate 将方法调用传递到另一个对象。

    class Article < ActiveRecord::Base
      has_one :commentable
    
      delegate :comments, :to => :commentable
    end
    

    编辑:

    我假设你不打算在你的例子中使用常量文章,因为这两种方式都行不通。这些方法是实例方法,需要用作:

    article = Article.first
    
    article.commentable.comments
    article.comments (Equivalent to above)