ruby-on-rails – 为什么Rails orphan通过关联连接多态的记录?
发布时间:2020-12-16 21:01:23 所属栏目:百科 来源:网络整理
导读:提案文档可以分为许多不同的部分类型(文本,费用,时间表)等 这里使用连接表上的多态关联建模. class Proposal ActiveRecord::Base has_many :proposal_sections has_many :fee_summaries,:through = :proposal_sections,:source = :section,:source_type = 'F
提案文档可以分为许多不同的部分类型(文本,费用,时间表)等
这里使用连接表上的多态关联建模. class Proposal < ActiveRecord::Base has_many :proposal_sections has_many :fee_summaries,:through => :proposal_sections,:source => :section,:source_type => 'FeeSummary' end class ProposalSection < ActiveRecord::Base belongs_to :proposal belongs_to :section,:polymorphic => true end class FeeSummary < ActiveRecord::Base has_many :proposal_sections,:as => :section has_many :proposals,:through => :proposal_sections end 虽然#create工作正常 summary = @proposal.fee_summaries.create summary.proposal == @propsal # true #new不要 summary = @proposal.fee_summaries.new summary.proposal -> nil 它应该返回零吗? 在常规的has_many和belongs_to初始化但尚未存在的记录仍将返回其父关联(内置在内存中). 为什么这不起作用,是否是预期的行为? Schema.rb create_table "fee_summaries",:force => true do |t| t.datetime "created_at",:null => false t.datetime "updated_at",:null => false end create_table "proposal_sections",:force => true do |t| t.integer "section_id" t.string "section_type" t.integer "proposal_id" t.datetime "created_at",:null => false end create_table "proposals",:null => false end ruby2.0 解决方法
ActiveRecord无法知道该proposal.fee_summaries是来自fee_summary.proposal的反向关联.这是因为你可以定义你自己的关联名称,对它有额外的约束等等 – 自动导出哪些关联是相反的,如果不是不可能的话,这将是非常困难的.因此,即使对于大多数简单的情况,您也需要通过关联声明中的inverse_of选项明确告诉它.以下是简单直接关联的示例:
class Proposal < ActiveRecord::Base has_many :proposal_sections,:inverse_of => :proposal end class ProposalSection < ActiveRecord::Base belongs_to :proposal,:inverse_of => :proposal_sections end 2.0.0-p353 :001 > proposal = Proposal.new => #<Proposal id: nil,created_at: nil,updated_at: nil> 2.0.0-p353 :002 > section = proposal.proposal_sections.new => #<ProposalSection id: nil,proposal_id: nil,updated_at: nil> 2.0.0-p353 :003 > section.proposal => #<Proposal id: nil,updated_at: nil> 不幸的是,inverse_of不支持间接(通过)和多态关联.所以在你的情况下,没有简单的方法让它工作.我看到的唯一解决方法是保留记录(使用create),因此AR只能按键查询关系并返回正确的结果. 查看文档以获取更多示例和说明:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |