has_many通过自定义类型的多态

时间:2012-07-31 15:06:43

标签: ruby-on-rails ruby ruby-on-rails-3

我有两个应用程序,一个用作API,具有只读访问权限和一个主要应用程序。在主应用程序中,我有很多通过多态关系。主应用程序中的模型看起来像这样,并且效果很好:

class Category < ActiveRecord::Base
  has_many :category_associations
  has_many :posts, through: :category_associations
  has_many :pages, through: :category_associations
end

class Post < ActiveRecord::Base
  has_many :category_associations, as: :associated
  has_many :categories, as: associated, through: :category_associations, source: :post
end

class Page < ActiveRecord::Base
  has_many :category_associations, as: :associated
  has_many :categories, as: associated, through: :category_associations, source: :post
end

class CategoryAssociation
  belongs_to :category
  belongs_to :associated, polymorphic: true
end

现在对于第二个应用程序,我需要访问相同的表,但我的类名称会有所不同,这会影响即使使用source_type也无法覆盖的类型字段。:

class Category < ActiveRecord::Base
  has_many :category_associations
  has_many :articles, through: :category_associations
  has_many :static_contents, through: :category_associations
end

class Article < ActiveRecord::Base
  self.table_name = 'posts'

  has_many :category_associations, as: :associated
  has_many :categories, as: associated, through: :category_associations, source: :article, source_type: 'Post'
end

class StaticContent < ActiveRecord::Base
  self.table_name = 'pages'

  has_many :category_associations, as: :associated
  has_many :categories, as: associated, through: :category_associations, source: :static_content, source_type: 'Page'
end

class CategoryAssociation
  belongs_to :category
  belongs_to :associated, polymorphic: true
end

我收到以下错误:

=> Posts.first.categories

# ActiveRecord::HasManyThroughAssociationPointlessSourceTypeError: Cannot have a has_many :through association 'Post#categories' with a :source_type option if the 'CategoryAssociation#category' is not polymorphic. Try removing :source_type on your association.

当我从类别

中抓取帖子时,似乎也是如此

1 个答案:

答案 0 :(得分:-1)

您是否尝试将polymorphic:true置于类别belongs_to?这似乎是错误消息指向的方向,但我不确定

class CategoryAssociation
  belongs_to :category, polymorphic: true
  ...
end