给定一个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
块关联模型:
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 -嵌套形式/