[英]Polymorphic model and has_many through
I have a polymorphic
model Document
and multiple models with documents linked. 我有一个polymorphic
模型Document
和链接了文档的多个模型。 One of which the CustomerPlan
model that has_many documents, as: :linkable
. 其中has_many documents, as: :linkable
的CustomerPlan
模型之一has_many documents, as: :linkable
。 This works fine. 这很好。
In addition I have a Company
model that has_many :customer_plans
. 另外,我有一个具有has_many :customer_plans
的Company
模型。 As such an instance of Company should also have many documents. 因此,公司的一个实例也应该有很多文件。 How do I properly set up the has_many relation between the Company
model and the Document
model? 如何在Company
模型和Document
模型之间正确设置has_many关系?
Currently: 目前:
Schema: 架构:
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
Models: 楷模:
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
According to my understanding of your question, 根据我对您问题的理解,
if Company
has_many :customer_plans
and CustomerPlan
has_many :documents
, then you could have Company
has_many :documents, through: :customer_plans
如果Company
has_many :customer_plans
和CustomerPlan
has_many :documents
,则可以has_many :documents, through: :customer_plans
拥有Company
has_many :documents, through: :customer_plans
I believe you should be able to do something like: 我相信您应该可以执行以下操作:
class Company < ActiveRecord::Base
has_many :customer_plans
has_many :documents, through: :customer_plans
end
UPDATE 更新
based on the new information of company having other documents through other associations, I'd probably go about it this way: 根据公司通过其他协会拥有其他文件的新信息,我可能会这样处理:
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
Let me know if that works 让我知道是否可行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.