多态模型和has_many通过

时间:2016-07-07 11:31:31

标签: ruby-on-rails polymorphic-associations

我有一个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

2 个答案:

答案 0 :(得分:0)

根据我对你的问题的理解,

如果Company has_many :customer_plansCustomerPlan 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

如果有效,请告诉我