我有一个polymorphic
模型Document
和多个连接文档的模型。其中一个CustomerPlan
模型has_many documents, as: :linkable
。这很好。
此外,我有一个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
答案 0 :(得分:0)
根据我对你的问题的理解,
如果Company
has_many :customer_plans
和CustomerPlan
has_many :documents
,那么您可以Company
has_many :documents, through: :customer_plans
答案 1 :(得分:0)
我相信你应该能够做到这样的事情:
class Company < ActiveRecord::Base
has_many :customer_plans
has_many :documents, through: :customer_plans
end
<强>更新强>
基于通过其他协会提供其他文件的公司的新信息,我可能会这样做:
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
如果有效,请告诉我