Rails属于具有范围的STI表

时间:2017-03-31 22:34:03

标签: ruby-on-rails scope associations ruby-on-rails-5 sti

我有一个STI表“派对”如下:

# 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

和“party_contacts”表格如下:

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

我想查询“party_contacts”以获取所有供应商/客户联系人的列表。如何编写“party_contacts”的范围(或者它应该在父模型中)?

我正在尝试以下范围:

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

但是得到错误:

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

1 个答案:

答案 0 :(得分:0)

谢谢@Swards,我想了一会儿。范围应如下:

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

构建正确的查询:

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 []>

此处partyjoins(:party)中是单数的,因为它是belongs_to关系。 partiesincludes(:parties)中的where(parties:{...})是复数形式,因为它是表格的名称。