小编tre*_*sen的帖子

Rails中的双向多态连接模型?

我正在开发一个多站点CMS,它具有站点间交叉发布的概念.几种类型的内容(文章,事件,Bios等)可以与许多网站相关联,而网站可以包含许多内容.内容片段和站点之间的多对多关联还必须支持每个相关内容项的一些共同属性 - 站点起源的概念(这是内容出现的原始站点吗?)以及概念给定关联网站上给定内容的"主要"和"次要"内容状态.

我的想法是创建一个名为ContentAssociation的多态连接模型,但是我很难让多态关联按照我的预期行事,而且我想知道我是否会这样做是错的.

这是我对连接表和模型的设置:

create_table "content_associations", :force => true do |t|
  t.string   "associable_type"
  t.integer  "associable_id"
  t.integer  "site_id"
  t.boolean  "primary_eligible"
  t.boolean  "secondary_eligible"
  t.boolean  "originating_site"
  t.datetime "created_at"
  t.datetime "updated_at"
end

class ContentAssociation < ActiveRecord::Base
  belongs_to :site
  belongs_to :associable, :polymorphic => true
  belongs_to :primary_site, :class_name => "Site", :foreign_key => "site_id" 
  belongs_to :secondary_site, :class_name => "Site", :foreign_key => "site_id"
  belongs_to :originating_site, :class_name => "Site", :foreign_key => "site_id"
end

class Site < ActiveRecord::Base
  has_many :content_associations, :dependent => :destroy 
  has_many :articles, :through => :content_associations, :source …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails polymorphic-associations ruby-on-rails-3

3
推荐指数
1
解决办法
2498
查看次数