繁体   English   中英

多态模型和has_many通过

[英]Polymorphic model and has_many through

我有一个polymorphic模型Document和链接了文档的多个模型。 其中has_many documents, as: :linkableCustomerPlan模型之一has_many documents, as: :linkable 这很好。

另外,我有一个具有has_many :customer_plansCompany模型。 因此,公司的一个实例也应该有很多文件。 如何在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_plansCustomerPlan has_many :documents ,则可以has_many :documents, through: :customer_plans拥有Company has_many :documents, through: :customer_plans

我相信您应该可以执行以下操作:

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

让我知道是否可行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM