简体   繁体   English

两个STI /多态之间的关联

[英]Association between two STI/Polymorphic

Currently I have a Group and GroupPeriod that contains the same attributes 目前,我有一个包含相同属性的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

The logic is Group has many GroupPeriods. 逻辑是Group具有许多GroupPeriods。 But then I have different groups; 但是那时我有不同的群体。 Bill and Pay. 账单和付款。 So I'm creating an STI for both BillGroup and PayGroup: 所以我正在为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

The issue I'm having is that each group will have many PayPeriod or BillPeriod. 我遇到的问题是每个组将有许多PayPeriod或BillPeriod。 So I created a GroupPeriod to link 所以我创建了一个GroupPeriod进行链接

class GroupPeriod < ApplicationRecord
  belongs_to :group
end

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

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

My question is, how can I ensure through inheritance, I can be flexible that 我的问题是,如何确保通过继承,我可以灵活地做到

  1. BillGroup has many BillPeriods; BillGroup有许多BillPeriods;
  2. PayGroup has many PayPeriods; PayGroup有许多PayPeriods;

without overlapping (BillGroup will not see PayPeriod and vice versa) with each other? 彼此没有重叠(BillGroup不会看到PayPeriod,反之亦然)? At the same time, is this a bad practice that I should make them into 2 different tables for each BillGroup and PayGroup? 同时,我应该将每个BillGroup和PayGroup分别放入2个不同的表中,这是一种不好的做法吗?

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

your model looks something like this , rest depends on your associations. 您的模型看起来像这样,其余部分取决于您的关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM