【问题标题】:Has Many Through Association Polymorphic Error有很多通过关联多态错误
【发布时间】:2010-09-07 00:22:48
【问题描述】:

随着 Rails 3 的推出,我想知道是否有一些新方法可以通过与多态模型的关联来实现 has_many :如果不是,那么最好的方法是什么?

这就是我正在使用的东西

class Page < ActiveRecord::Base
end

class Text < ActiveRecord::Base
end

class Picture < ActiveRecord::Base
end

文本和图片是属于一个或多个页面的内容 -- 每个页面都有一个或多个内容元素(文本或图片)。我希望能够做到这一点:

page.content => ["text item 1", "text item 2", "picture 1"]
picture.pages => ["page 3", "page 7"]

如上所述,我正在使用 Rails 3。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我会使用 HMT 和 STI:

    class Page < ActiveRecord::Base
      has_many :assets, :through => :page_components
    
      def content
        self.assets
      end
    end
    
    class PageComponent < ActiveRecord::Base
      # could also use HABTM
      belongs_to :page
      belongs_to :asset
    end
    
    class Asset < ActiveRecord::Base
      has_many :pages, :through => :page_components
    end
    
    class Text < Asset
      # inherits .pages association method from Asset
    end
    
    class Picture < Asset
      # so does this.
    end
    
    # class Video < Asset...
    

    【讨论】:

      【解决方案2】:

      Rails 3 和 2 没有区别。

      class Page < ActiveRecord::Base
        belongs_to :text  # foreign key - text_id
        belongs_to :picture     # foreign key - picture_id
      end
      class Text < ActiveRecord::Base
        has_many : pictures
        has_many :pictures, :through => :pages
      end
      class Picture < ActiveRecord::Base
        has_many :assignments
        has_many :texts, :through => :pages
      end
      

      第二个想法

      你的最后一条评论让我想到你可能有大量的 content_types,或者更多的是 content_types 可能能够在客户端生成。

      这是另一种选择,为什么不只制作一个模型 Page - 并使其具有反映其 content_type 的属性。然后你可以像这样与他们建立关系..

      @show_texts = Page.find(:all).select{ |p| p.text != nil }.collect{|p| p.id}.inspect
      

      等等等等..只是一个想法。老实说,我会尝试将上面的代码重构为对 SQL 友好的版本,因为有很多方法可以用来访问数据库。

      【讨论】:

      • 这只是一对多。我需要多对多。我还应该注意,在上面的示例中,我只有 2 种内容类型,但我可以有更多...
      • 最好忽略多态方式,按照您上面的建议进行操作。但是,随着我添加更多内容类型,Page 将有很多“belongs_to”语句...
      • 我不确定我是否了解您的大局。模型本身会在客户端生成吗?您将拥有多少个“content_types”?这至少会为你提供很多服务。我将在上面更新替代方案。
      • 上述解决方案当然是个有趣的想法,我会考虑一下。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2017-09-03
      • 2018-01-28
      • 2012-04-29
      相关资源
      最近更新 更多