2017-03-31 5 views
0

Ich habe eine STI-Tabelle "Parteien" wie folgt:Rails belongs_to STI Tabelle mit Rahmen

# app/models/party.rb 
class Party < ApplicationRecord 
    has_many :party_contacts 

    scope :vendors, -> { where(type: 'Party::Vendor') } 
    scope :customers, -> { where(type: 'Party::Customer') } 
end 

# app/models/party/vendor.rb 
class Party::Vendor < Party 
end 

# app/models/party/customer.rb 
class Party::Customer < Party 
end 

Und "party_contacts" Tabelle wie folgt:

class PartyContact < ApplicationRecord 
    belongs_to :party 

    scope :of_vendors, -> {# fetch all contacts belongs to all vendors logic } 
    scope :of_customers, -> {# fetch all contacts belongs to all customers logic } 
end 

Ich möchte Abfrage machen auf " party_contacts ", um eine Liste aller Händler/Kundenkontakte zu erhalten. Wie kann ich den Umfang für "party_contacts" schreiben (oder sollte es im übergeordneten Modell sein)?

Ich versuche folgende Bereiche:

scope :of_vendors, -> { joins(:party).includes(:party).where(party: { type: "Party::Vendor" }) } 
scope :of_customers, -> { joins(:party).includes(:party).where(party: { type: "Party::Customer" }) } 

Aber bekommen Fehler:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "party" 
LINE 1: ...parties"."id" = "party_contacts"."party_id" WHERE "party"."t... 
+1

'wo (Partei:' sollte – Swards

Antwort

0

Danke @Swards, dachte ich es aus, bevor eine Weile einfach. Der Umfang sollte wie folgt lauten:

scope :of_vendors, -> { joins(:party).includes(:parties).where(parties: { type: "Party::Vendor" }) } 
scope :of_customers, -> { joins(:party).includes(:parties).where(parties: { type: "Party::Customer" }) } 

Es richtige Abfrage-Konstrukte:

2.4.0 :042 > PartyContact.of_vendors 
PartyContact Load (8.8ms) SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1 [["type", "Party::Vendor"]] 
=> #<ActiveRecord::Relation []> 
2.4.0 :043 > PartyContact.of_customers 
PartyContact Load (0.5ms) SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1 [["type", "Party::Customer"]] 
=> #<ActiveRecord::Relation []> 

Hier party ist einzigartig in joins(:party) wie es belongs_to Beziehung ist. Und parties ist Plural in includes(:parties) und where(parties:{...}) wie es Name der Tabelle ist.

+0

seltsam, dass 'enthält (Plural:. Parteien)' Werke Es sollte nur dem Namen Assoziationen erlauben Es sieht aus wie es sie ignorieren kann.. – Swards

Verwandte Themen