【发布时间】:2014-01-24 16:06:25
【问题描述】:
给定一个ContentBlock 模型:
class ContentBlock < ActiveRecord::Base
has_one :block_association
has_one :image, through: :block_association, source: :content, source_type: "Image"
has_one :snippet, through: :block_association, source: :content, source_type: "Snippet"
accepts_nested_attributes_for :image, allow_destroy: true
accepts_nested_attributes_for :snippet, allow_destroy: true
end
BlockAssociation 模型:
class BlockAssociation < ActiveRecord::Base
belongs_to :content_block
belongs_to :content, polymorphic: true
end
片段模型:
class Snippet < ActiveRecord::Base
has_one :block_association, as: :content
has_one :content_block, through: :block_association
validates :body, presence: true
end
我需要做的:
@content_block.build_snippet
但这给出了:
undefined method 'build_snippet' for #<ContentBlock:0x007ffb7edde330>
我将如何达到预期的效果?
表格应该是这样的:
<%= simple_form_for @content_block do |f| %>
<%= f.simple_fields_for f.object.snippet || f.object.build_snippet do |sf| %>
<%= sf.input :body %>
<% end %>
<% end %>
(最初我认为content_block 只是belong_to :content, polymorphic: true,但由于content 有多种类型,这似乎不够。)
这有点接近我正在做的事情,但我无法完全理解它:http://xtargets.com/2012/04/04/solving-polymorphic-hasone-through-building-and-nested-forms/
【问题讨论】:
-
我想我不明白你想要完成什么。你想要一个 content_block,它有一个 sn-p 和一个图像。您想将关联的 sn-p 和图像称为内容。我认为您根本无法使“build_sn-p”正常工作,但可以执行“@content_block.content = Snippet.create(...)”之类的操作
标签: ruby-on-rails ruby-on-rails-4 associations polymorphic-associations has-one-through