![](/img/trans.png)
[英]Rails class name/type not working for a polymorphic has_many :through
[英]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.