多态模型和has_many通过
问题描述:
我有一个polymorphic
模型Document
和与文件链接的多个模型。其中之一CustomerPlan
型号has_many documents, as: :linkable
。这工作正常。多态模型和has_many通过
另外我有一个Company
模型has_many :customer_plans
。因为这样的公司应该也有很多文件。如何正确设置Company
模型和Document
模型之间的has_many关系?
目前:
模式:
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
答
根据我对你的问题的理解,
如果Company
has_many :customer_plans
和CustomerPlan
has_many :documents
,那么你可能有Company
has_many :documents, through: :customer_plans
答
我相信你应该能够做这样的事情:
class Company < ActiveRecord::Base
has_many :customer_plans
has_many :documents, through: :customer_plans
end
UPDATE
基于具有通过其他协会的其他文件公司的新的信息,我大概就这样吧:
class Company < ActiveRecord::Base
has_many :customer_plans
has_many :customer_plan_documents, through: :customer_plans, source: :documents
# you can later do other document associations here
end
让我知道如果作品
公司也可以通过其他模型的文件(因此多态性),你应该指定一个has_many关联分别为每个? – Matthias