У меня есть 2 приложения, которые служат API и имеют доступ только для чтения, и тот, который является основным приложением. В основном приложении у меня есть много полиморфных отношений. Модели в основном приложении выглядеть так, и они прекрасно работают:has_many через полиморфный с настраиваемым типом
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.
также кажется, что когда я захватить сообщения из категории
Попробуйте ассоциации обмена: ** has_many category_associations ** to ** has_many categories **. другие уходят. Я думаю, что в «основной» ассоциации, которая является ** has_many: category_association **, должна быть информация о полиморфной модели CategoryAssociation. has_many относится к категории, которая не является полиморфной. Поэтому source_type с источником не нужен и дает вам ошибку. – rado