两个STI /多态的关联

时间:2017-09-01 12:31:33

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

目前我有一个包含相同属性的Group和GroupPeriod

  create_table "groups", force: :cascade do |t|
    t.bigint "company_id"
    t.string "name"
    t.date "cutoff_date"
    t.date "processing_date"
    t.integer "working_days"
    t.integer "working_hours"
    t.integer "status"
    t.float "basic_pay"
    t.string "type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["company_id"], name: "index_groups_on_company_id"
  end

  create_table "group_periods", force: :cascade do |t|
    t.bigint "company_id"
    t.date "start_date"
    t.date "end_date"
    t.string "type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "group_id"
    t.index ["company_id"], name: "index_group_periods_on_company_id"
    t.index ["group_id"], name: "index_group_periods_on_group_id"
  end

逻辑是Group有很多GroupPeriods。但后来我有不同的群体;比尔和支付。所以我正在为BillGroup和PayGroup创建一个STI:

class Group < ApplicationRecord
  has_many :group_periods
end

class BillGroup < Group
  #=> has_many :bill_periods??
end

class PayGroup < Group
  #=> has_many :pay_periods??
end

我遇到的问题是每个组都会有很多PayPeriod或BillPeriod。所以我创建了一个GroupPeriod来链接

class GroupPeriod < ApplicationRecord
  belongs_to :group
end

class BillPeriod < GroupPeriod
  #=> belongs_to :bill_group??
end

class PayPeriod < GroupPeriod
  #=> belongs_to :pay_group??
end

我的问题是,如何通过继承确保我可以灵活地

  1. BillGroup有很多BillPeriods;
  2. PayGroup有很多PayPeriods;
  3. 没有重叠(BillGroup不会看到PayPeriod,反之亦然)?与此同时,这是一个不好的做法,我应该为每个BillGroup和PayGroup将它们分成两个不同的表吗?

1 个答案:

答案 0 :(得分:1)

class Group < ApplicationRecord
  has_many :group_periods
end

class Period < ApplicationRecord
  belongs_to :group
  belongs_to :group_periods, polymorphic: true
end

class BillPeriod < GroupPeriod
  has_many :periods, as: :group_periods, dependent: :destroy
end

class PayPeriod < GroupPeriod
  has_many :periods, as: :group_periods, dependent: :destroy
end

你的模型看起来像这样,休息取决于你的关联。