【问题标题】:Rails polymorphic has_one buildRails 多态 has_one 构建
【发布时间】: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 #&lt;ContentBlock:0x007ffb7edde330&gt;

我将如何达到预期的效果?

表格应该是这样的:

<%= 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


【解决方案1】:
class ContentBlock < ActiveRecord::Base      
  has_one :snippet, through: :block_association, source: :content, source_type: "Snippet"
end

这告诉 rails,您希望 ContentBlock 的实例(让 content_block 这个实例)通过 BlockAssociation 拥有一个名为“sn-p”的假类型“内容”的 Snippet 实例。因此,ContentBlock 实例应该能够响应 content_block.content,这将返回 sn-p 和/或图像的集合(我在 code-sn-ps 中省略了图像部分)。 content_block 是如何只调用尚未有人知道的 sn-p 内容的。

你的 BlockAssociation 模型知道什么:

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

它知道它属于一个 content_block 并且知道(因为它会响应内容)一个或多个具有 content_type('Snippet')和 content_id(1 或任何 sn-ps id)的内容,组合那些与sn-p的关系

现在你缺少的是片段部分:

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 如何调用这种类型的内容,因为你想区分 image-content 和 sn-p-content。现在 content_block.sn-p_content 应该返回 sn-p 并且 sn-p.block_content 应该返回 block_content。

我希望我没有搞砸任何事情,这些关系总是让我头晕目眩

【讨论】:

  • snippet_content 未定义为content_block 模型中的关系,因此调用block_block.snippet_content 在这里不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多