【发布时间】:2011-01-08 13:42:31
【问题描述】:
我有一个管理借方和贷方的发票系统。基本上,发票金额是通过借方的总和获得的,余额是通过贷方的总和减去总金额得出的。
我用四个模型来做这个。
- 发票
- 订单项
- 借记
- 信用
它的工作方式是通过具有称为可记录的多态关联的连接模型(行项)。乍一看,一切似乎都正常工作。 但是,检查订单项显示虽然 recordable_id 显示正常,但 recordable_type 为 nil。
下面是代码分解:
class Invoice < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
has_many :debits, :through => :line_items, :as => :recordable
has_many :credits, :through => :line_items, :as => :recordable
end
class LineItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :recordable, :polymorphic => true
belongs_to :credit, :class_name => "Credit", :foreign_key => "recordable_id"
belongs_to :debit, :class_name => "Debit", :foreign_key => "recordable_id"
end
class Credit < ActiveRecord::Base
has_many :line_items, :as => :recordable, :dependent => :destroy
end
class Debit < ActiveRecord::Base
has_many :line_items, :as => :recordable, :dependent => :destroy
end
谁能在这里指出我正确的方向?
【问题讨论】:
-
如何将 line_items 分配给贷方/借方?
-
这通过 has_many :through 自动发生。因此,当您执行 Invoice.last.credits
-
不应该是
:as是has_many :line_items,而不是has_many :through关联? -
否,因为 invoice_id 是 line_item 对象上的一个字段。多态性仅适用于确实使用 :as 在其 :has_many 声明中的借方和贷方对象。
标签: ruby-on-rails ruby polymorphic-associations has-many-through