我有以下参数:
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"06Us9R1wCPCJsD06TN7KIV/2ZeH4dJlZVqc12gpKBbo=",
"run"=>{"box_id"=>"1"}, "tapes"=>{"1"=>{"tape_id"=>"1"},
"2"=>{"tape_id"=>"2"}, "3"=>{"tape_id"=>"3"}}, "commit"=>"Create Run"}}
我想创建一个框ID为1的新“运行”,然后将磁带1 2和3关联到此运行,框ID为1
我不确定需要进入控制器的代码,我确实尝试过:
def create
@run = Run.new(params[:run])
@tape_ids = @run.build_tape(params[:run][:tapes])
@run.save
当我提交下面的表格时,它会使用正确的方框创建一个新的“运行”,但不会将任何磁带与之相关联。
<%= form_for(@run) do |f| %>
<% if @run.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@run.errors.count, "error") %> prohibited this tape
from being saved:
</h2>
<ul>
<% @run.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :box_id %>
<br/>
<%= f.text_field :box_id %>
</div>
<% (1..3).each do |index| %>
<%= fields_for :tapes do |ff| %>
<div class="field">
<%= ff.label :tape_id , :index => index%>
<%= ff.text_field :tape_id, :index => index %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:0)
如果您没有accepts_nested_attributes_for
,那么这可能会有效。我不知道build_tape
应该做什么,但以下内容将为您提供一系列tape_ids:
@tape_ids = params[:run][:tapes].map { |k, v| v["tape_id"].to_i }
要完成关联,您可以执行类似
的操作params[:run][:tapes].each do |k, v|
t = Tape.find(v["tape_id"].to_i)
t.run = @run
t.save
end