首页 > 解决方案 > 构建多态关联 Rails

问题描述

所以我有以下

class OptionOfSingleChoice < ApplicationRecord
  has_many  :option_choices, as: :choiceable
end

class OptionChoice < ApplicationRecord
  belongs_to :choiceable, polymorphic: true, optional: true
end

在 OptionOfSingleChoice 控制器的新操作中,我正在执行以下操作:

def new
    @optionofsinglechoice = OptionOfSingleChoice.new()
    setup_three_default_choices()
    3.times {@optionofsinglechoice.option_choices.build}
end

以及新操作的视图

<div class="form-group">
    <%= test.fields_for :option_choices do |builder|  %>
        <%= render 'option_choices/form', :f => builder  %>
    <% end %>
</div>

option_choice 的表单视图如下所示

<div class="form-group">

  <%= f.text_field(:name, :class => 'form-control') %>
  <%= f.text_field(:price, :class => 'form-control') %>
  <%= f.file_field :choice_image, multiple: false, direct_upload: false,:class => 'form-control' %>

</div>

我现在的问题是,我希望 option_choice 的表单渲染 3 次,但实际上它只渲染了 1 次。我不明白为什么,但我怀疑这是因为 Choisable 没有创建。当我查看 OptionChoice 对象时,它们看起来像这样:

<OptionChoice id: nil, name: nil, price: nil, choiceable_id: nil, choiceable_type: "OptionOfSingleChoice", created_at: nil, updated_at: nil>

我的猜测是我需要以某种方式构建 :choiceable 。希望你能帮助我

标签: ruby-on-railsnestedpolymorphic-associations

解决方案


对不起,我忘了添加accepts_nested_attributes_for:option_choices


推荐阅读