1

我有 2 个应用程序,一个用作 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.

似乎当我从类别中获取帖子时

4

1 回答 1

-1

你试过把polymorphic:true这个类别belongs_to吗?似乎这是错误消息点所指向的方向,尽管我不确定

class CategoryAssociation
  belongs_to :category, polymorphic: true
  ...
end
于 2012-08-01T02:13:53.170 回答