0

給定一個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/

+0

我不認爲我明白你要完成的任務。你想有一個content_block,它有一個片段和一個圖像。你想引用相關的片段和圖像作爲內容。 我不認爲你可以讓「build_snippet」工作,但它可以做一些像「@ content_block.content = Snippet.create(...)」 – Ninigi

回答

0
class ContentBlock < ActiveRecord::Base  
    has_one :snippet, through: :block_association, source: :content, source_type: "Snippet" 
end 

Thi s告訴rails,你想讓ContentBlock的實例(讓content_block這個實例)有一個通過BlockAssociation僞造的「內容」的Snippet實例,稱爲「snippet」。因此,ContentBlock實例應該能夠響應content_block.content,這會讓一段代碼片斷和/或圖像(我遺漏了代碼片段中的圖像部分)的集合。 content_block如何只能調用沒有人知道的片段內容。

什麼是你BlockAssociation型號知道:

class BlockAssociation < ActiveRecord::Base 
    belongs_to :content_block 
    belongs_to :content, polymorphic: true 
end 

它知道它屬於content_block並且知道其中有一個CONTENT_TYPE(「段」)的一個或多個內容和(因爲它會以響應內容)的content_id(1或任何片段ID是),這些的組合使關係片斷

現在是你所缺少的是摘錄部分:

class Snippet < ActiveRecord::Base 
    has_one :block_association, :as => :snippet_content 
    has_one :content_block, :through => :content_association # I'm actually not quite sure of this 
end 

它告訴block_association如何調用這種類型的內容,因爲您希望在圖像內容和片段內容之間有所不同。現在content_block.snippet_content應該返回片段,而snippet.block_content應該返回block_content。

我希望我沒惹什麼都漲,這些關係八方通讓我的頭紡紗

+0

「snippet_content」沒有被定義爲一種關係在'content_block'模型中,調用'block_block。snippet_content'在這裏不起作用 –