【问题标题】:Association between two STI/Polymorphic两个 STI/多态性之间的关联
【发布时间】:2017-09-01 12:31:33
【问题描述】:

目前我有一个 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 有许多 PayPeriod;

彼此不重叠(BillGroup 不会看到 PayPeriod,反之亦然)?同时,我应该为每个 BillGroup 和 PayGroup 将它们放入 2 个不同的表中,这是一种不好的做法吗?

【问题讨论】:

  • 你可以试试多态关联,更多信息请访问guides.rubyonrails.org/association_basics.html
  • 这是否意味着每次我必须使用多态关联使用类型和 id 来确定组的范围? @PardeepSaini
  • 是的,您可以通过账单或支付实例获取所有期间。

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


【解决方案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

你的模型看起来像这样,其余的取决于你的联想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多