【发布时间】:2017-01-23 23:16:20
【问题描述】:
我有一个包含模型的应用,我们称之为 Box、Stock、Experiment 和 Sample。以下是 ActiveRecord 关系的样子:
class Box
has_many :stocks
accepts_nested_attributes_for :stocks
end
class Stock
belongs_to :box
has_many :samples
end
class Experiment
has_many :samples
accepts_nested_attributes_for :samples
end
class Sample
belongs_to :experiment
belongs_to :stock
end
我想在我的 Box#show 页面上有一个按钮,名为“Generate Experiment From Box”。理想情况下,这将带我进入我的 Experiment#new 页面,其中预先填充了 Samples 的嵌套字段 - 每个 Stock 一个 Sample。 样本不应保存为对象,因为我希望用户能够在保存实验之前修改样本。但是,我目前无法让嵌套字段预填充。
app/views/boxes/show.html.erb
<%= link_to 'Generate New Experiment Box', new_experiment_path(box_id: @box.id) %>
app/controllers/experiments/experiments_controller.rb
def new
if params[:box_id]
stocks = Box.find(params[:box_id]).stocks
samples_attributes = stocks.map { |stock| { stock_id: stock.id } }
@experiment = Experiment.new(samples_attributes: samples_attributes)
else
@experiment = Experiment.new
end
end
app/views/experiments/new.html.erb
<%= simple_form_for(@experiment) do |f| %>
<div>
#various form inputs
</div>
<div>
<table>
<thead>#column headers</thead>
<tbody id="samples-table">
<%= f.simple_fields_for :samples, f.object.samples.order(:id) do |sample_fields| %>
<%= render 'sample_fields', f: sample_fields %>
<% end %>
</tbody>
</table>
<div id="Links">
<%= link_to_add_association "Add Samples to Experiment", f, :samples, :"data-association-insertion-node" => 'tbody#samples-table', :"data-association-insertion-method" => 'append' %>
</div>
</div>
<% end %>
app/views/experiments/_sample_fields.html.erb
<tr class="nested-fields form-inline form-table-row">
<td>#various text fields</td>
<td>#various text fields</td>
</tr>
非常感谢任何帮助!我已经尝试了几种不同的方法来解决这个问题,但仍然无法填充嵌套字段。谢谢!
【问题讨论】:
-
您是否确认:a)
params[:box_id]确实存在? b)stocks和 c) 中有一些东西对samples_attributes有用吗?然后 d)@experiment.samples实际上包含什么?即...在什么时候填充失败? :) -
是的,'params[:box_id]' 正在被传输,'stocks' 等于 Stock 对象的 ActiveRecord 集合,'samples_attributes' 是一个对象数组(samples_attributes.first = {:stock_id =>1}),'@experiment.samples' 是未保存的 Sample 对象的 ActiveRecord 集合。我实际上能够在这里解决问题 - 'f.object.samples.order(:id)' 没有工作,但 '@experiment.samples' 工作。谢谢!
标签: ruby-on-rails nested-forms cocoon-gem