简体   繁体   中英

Rails: Two tables has_many a single table

What's a better way to achieve this?

class Opf < ActiveRecord::Base
    has_many :budget_items, dependent: :destroy, foreign_key: 'budget_id'
end

class Voucher < ActiveRecord::Base
    has_many :budget_items, dependent: :destroy, foreign_key: 'budget_id'
end

class BudgetItem < ActiveRecord::Base
    belongs_to :opf
    belongs_to :voucher
end

Opf and Voucher could has_many BudgetItem:

Opf.budget_items.build
Voucher.budget_items.build

The problem I get with this setup is they share the same foreign key.

For such cases you should consider polymorphic associations . They are easy to establish and maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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