給定一個ContentBlock
模型:Rails的多態HAS_ONE建立
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>
我將如何達到預期的結果?
的形式是這樣的:(我原本認爲content_block
只會belong_to :content, polymorphic: true
但似乎不足,由於多種content
類型)
<%= 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 %>
這是一種接近到我在做什麼,但我只是不能完全得到我的頭:http://xtargets.com/2012/04/04/solving-polymorphic-hasone-through-building-and-nested-forms/
我不認爲我明白你要完成的任務。你想有一個content_block,它有一個片段和一個圖像。你想引用相關的片段和圖像作爲內容。 我不認爲你可以讓「build_snippet」工作,但它可以做一些像「@ content_block.content = Snippet.create(...)」 – Ninigi