ruby-on-rails - 为什么 Rails 孤儿通过关联加入多态记录?

标签 ruby-on-rails ruby-on-rails-3 polymorphic-associations

提案文件可以分成许多不同的部分类型(文本、费用、时间表)等

这里使用连接表上的多态关联建模。

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 上,已初始化但未持久化的记录仍将返回其父关联(内置于内存中)。

为什么这不起作用,这是预期的行为吗?

模式文件
 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
    t.datetime "updated_at",   :null => false
  end

  create_table "proposals", :force => true do |t|
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

ruby 2.0
rails 3.2.14

最佳答案

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, created_at: nil, updated_at: nil> 
2.0.0-p353 :003 > section.proposal
 => #<Proposal id: nil, created_at: nil, updated_at: nil> 

不幸的是,inverse_of不支持间接( through )和多态关联。所以在你的情况下,没有简单的方法让它工作。我看到的唯一解决方法是保留记录(使用 create ),因此 AR 可以通过键查询关系并返回正确的结果。

查看文档以获取更多示例和解释:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods

关于ruby-on-rails - 为什么 Rails 孤儿通过关联加入多态记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678847/

相关文章:

ruby-on-rails - define_method 在调用方法之前不使用变量?

ruby-on-rails - 如何格式化 Rails 编辑字段中显示的值?

ruby-on-rails - Rspec 可以等待 ApplicationJob 的答复吗?

ruby - mongoid查询缓存

ruby-on-rails - 使用 grouped_options_for_select 设置默认值,使用 f.select

ruby-on-rails - rails gem : Running All Generators for given Namespace

ruby-on-rails - rails : has_many through with polymorphic association - will this work?

ruby-on-rails - 如何将acts-as-taggable-on 集成到RailsAdmin?

php - 多态关系和同名模型和 morphTo 函数

PostgreSQL:如何在不使用 "column definition list"的情况下从表中返回动态行?