Pod Mays
Pod Mays

Reputation: 2583

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.

Upvotes: 0

Views: 21

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

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

Upvotes: 1

Related Questions