У меня есть модель polymorphic
Document
и несколько моделей с документами, связанными. Одна из которых - модель CustomerPlan
, которая has_many documents, as: :linkable
. Это прекрасно работает.Полиморфная модель и has_many через
Кроме того, у меня есть модель Company
, которая has_many :customer_plans
. Поскольку такой экземпляр Компании также должен иметь много документов. Как правильно настроить отношение has_many между моделью Company
и моделью Document
?
В настоящее время:
схемы:
create_table "documents", force: :cascade do |t|
t.json "links"
t.integer "linkable_id"
t.string "linkable_type"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "documents", ["linkable_type", "linkable_id"], name: "index_documents_on_linkable_type_and_linkable_id", using: :btree
Модели:
class Document < ActiveRecord::Base
belongs_to :linkable, polymorphic: true
belongs_to :user
belongs_to :company
mount_uploaders :links, DocUploader
end
class CustomerPlan < ActiveRecord::Base
belongs_to :company
has_many :documents, as: :linkable
accepts_nested_attributes_for :documents
end
class Company < ActiveRecord::Base
has_many :customer_plans
has_many :documents
end
Компания может также иметь документы через другие модели (отсюда и полиморфизм), если вы указываете для каждой ассоциации has_many отдельно? – Matthias