ruby-on-rails - 构建多态关联 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 。希望你能帮助我
解决方案
对不起,我忘了添加accepts_nested_attributes_for:option_choices
推荐阅读
- javascript - 无法停止数组标记中的事件侦听器
- reactjs - Recharts 图表未正确呈现
- c++ - 已经存在的对新变量的列表分配混淆了 Rcpp 中的计算
- c# - MySql.Data.MySqlClient.MySqlException' 在 MySql.Data.dll 中没有解释
- ios - Mac:zsh:找不到命令:-s /(失败:将 iOS 备份重定向到外部硬盘)
- javascript - 更改 amCharts 饼图切片的颜色
- r - 您可以在 ggplot2 绘图的轴上反向缩放和居中吗?
- artificial-intelligence - 使用对话流的员工计划机器人
- html - Fullcalendar v5.7.0,星期模式下天数不分界线
- java - 在 git log 中搜索文件的所有版本需要很长时间