2016-07-07 99 views
0

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

回答

0

根據我對你的問題的理解,

如果Companyhas_many :customer_plansCustomerPlanhas_many :documents,那麼你可能有Companyhas_many :documents, through: :customer_plans

+0

公司也可以通過其他模型的文件(因此多態性),你應該指定一個has_many關聯分別爲每個? – Matthias

0

我相信你應該能夠做這樣的事情:

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 

讓我知道如果作品

+0

公司也可以通過其他模型(因此多態性)有文件,你應該指定一個has_many關聯分別爲每個? – Matthias

+0

更新了我的答案,以反映我可能要遵循的方法以實現 – oreoluwa