繁体   English   中英

has_many通过具有自定义类型的多态

[英]has_many through polymorphic with custom type

我有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也无法覆盖的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.

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

您是否尝试过将polymorphic:true放到分类belongs_to 似乎这是错误消息指向的方向,尽管我不确定

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM