2016-07-07 17 views
0

Ich habe ein polymorphic Modell Document und mehrere Modelle mit Dokumenten verknüpft. Eines davon ist das CustomerPlan Modell, das has_many documents, as: :linkable. Das funktioniert gut.Polymorphes Modell und has_many durch

Zusätzlich habe ich ein Company Modell, das has_many :customer_plans. Als solche sollte eine Instanz des Unternehmens auch viele Dokumente haben. Wie richte ich die has_many-Beziehung zwischen dem Modell Company und dem Modell Document richtig ein?

Derzeit:

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 

Modelle:

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 

Antwort

0

Nach meinem Verständnis Ihrer Frage,

wenn Companyhas_many :customer_plans und CustomerPlanhas_many :documents, dann sind Sie Companyhas_many :documents, through: :customer_plans

+0

Firma kann auch Dokumente über andere Modelle haben (daher der Polymorphismus) sollten Sie eine has_many-Zuordnung für jeden separat angeben? – Matthias

0

haben könnte ich glaube, sollte es möglich sein, etwas zu tun wie:

class Company < ActiveRecord::Base 
    has_many :customer_plans 
    has_many :documents, through: :customer_plans 
end 

UPDATE

auf der Grundlage der neuen Informationen von Unternehmen andere Dokumente durch andere Verbände haben, würde ich wahrscheinlich gehen Sie so auf diese Weise:

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 

Lassen Sie mich wissen, wenn das funktioniert

+0

Firma kann auch Dokumente über andere Modelle haben (daher der Polymorphismus), sollten Sie für jeden eine has_many-Zuordnung separat angeben? – Matthias

+0

Meine Antwort wurde aktualisiert, um einen Ansatz zu reflektieren, dem ich wahrscheinlich folgen würde, um das zu erreichen – oreoluwa