【问题标题】:Rails: Two tables has_many a single tableRails:两个表 has_many 一个表
【发布时间】:2015-11-16 14:41:44
【问题描述】:

有什么更好的方法来实现这一点?

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 和 Voucher 可以有_many BudgetItem:

Opf.budget_items.build
Voucher.budget_items.build

我在此设置中遇到的问题是它们共享相同的外键。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    对于这种情况,您应该考虑polymorphic associations。它们易于建立和维护。

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多