Jim*_*ers 5 ruby ruby-on-rails has-many-through polymorphic-associations
我有一个管理借方和贷方的发票系统.基本上,发票金额是通过其借方总和获得的,余额是通过获取其贷方总额并将其减去总金额得出的.
我正在用四种型号做这件事.
它的工作方式是通过一个连接模型(行项),它具有一个名为recordable的多态关联.乍一看似乎一切正常.但是,检查订单项会显示,当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
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我正确的方向吗?
你在你的班级中宣布了不明确的关联LineItem。
简而言之,belongs_to在你的班级中这样做:
belongs_to :invoice创建一个方法invoice,该方法在发票表中搜索引用的记录invoice_idbelongs_to :recordable, :polymorphic => true创建一个方法recordable,该方法recordable_type.underscore.pluralize在表中搜索引用的记录recordable_idbelongs_to :credit, :class_name => "Credit", :foreign_key => "recordable_id"创建一个方法credit,该方法在Credits表中搜索 引用的记录recordable_id。注意,recordable_type这里忽略了这一点。belongs_to :debit。由于您的 LineItem 可能只属于贷方或借方,因此额外声明这些关联是没有意义的。您可以通过协会参考这些内容recordable。
| 归档时间: |
|
| 查看次数: |
3703 次 |
| 最近记录: |