我正在开发一个多站点 CMS,它具有站点之间交叉发布的概念。多种类型的内容(文章、活动、简历等)可以与许多站点相关联,并且站点可以有许多内容。内容片段和站点之间的多对多关联还必须支持每个关联内容项的几个共同属性——站点起源的概念(这是内容出现的原始站点吗?)以及给定关联站点上给定内容的“主要”和“次要”内容状态。
我的想法是创建一个名为 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 => :associable, :source_type => "Article"
has_many :events, :through => :content_associations, :source => :associable, :source_type => "Event"
has_many :primary_articles, :through => :content_associations,
:source => :associable,
:source_type => "Article",
:conditions => ["content_associations.primary_eligible = ?" true]
has_many :originating_articles, :through => :content_associations,
:source => :associable,
:source_type => "Article",
:conditions => ["content_associations.originating_site = ?" true]
has_many :secondary_articles, :through => :content_associations,
:source => :associable,
:source_type => "Article",
:conditions => ["content_associations.secondary_eligible = ?" true]
end
class Article < ActiveRecord::Base
has_many :content_associations, :as => :associable, :dependent => :destroy
has_one :originating_site, :through => :content_associations,
:source => :associable,
:conditions => ["content_associations.originating_site = ?" true]
has_many :primary_sites, :through => :content_associations,
:source => :associable
:conditions => ["content_associations.primary_eligible = ?" true]
has_many :secondary_sites, :through => :content_associations,
:source => :associable
:conditions => ["content_associations.secondary_eligible = ?" true]
end
我已经尝试了上述关联声明的很多变体,但无论我做什么,我似乎都无法获得我想要的行为
@site = Site.find(2)
@article = Article.find(23)
@article.originating_site = @site
@site.originating_articles #=>[@article]
或这个
@site.primary_articles << @article
@article.primary_sites #=> [@site]
Rails 的内置多态性是否是用于影响站点及其各种内容之间的这些连接的错误机制?看起来它很有用,因为我需要以多对多的方式将多个不同的模型连接到一个通用模型,但是我很难找到以这种方式使用它的任何示例。
也许复杂性的一部分是我需要双向关联——即查看与给定文章关联的所有站点并查看与给定站点关联的所有文章。我听说过插件has_many_polymorphs,看起来它可以解决我的问题。但我在这里尝试使用 Rails 3,但不确定它是否受支持。
非常感谢任何帮助——即使它只是让我更加了解我对多态性在这种情况下的使用的不完全理解。
提前致谢!