访问params []值内的参数数组 [英] Accessing array of parameters inside the params[] value
问题描述
我有以下参数:
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"}}
I想要创建一个框号为1的新运行,然后将磁带1 2和3与框号为1的该运行关联起来
I want to create a new "Run" with the box id of 1 and then associate the tapes 1 2 and 3 to this run with the box id of 1
我不是确保需要什么代码进入控制器,我确实尝试过:
I am not sure what code needs to go into the controller, i did try:
def create
@run = Run.new(params[:run])
@tape_ids = @run.build_tape(params[:run][:tapes])
@run.save
当我提交下面的表单时,它将使用正确的框创建一个新的运行,但没有与之关联的磁带。
When i submit the form below, it creates a new Run with the correct box but associates no tapes with it.
<%= 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 %>
推荐答案
如果您不执行 accepts_nested_attributes_for
,那么也许可以。我不知道 build_tape
应该做什么,但是下面的内容可以使您使用一系列tape_ids:
If you're not doing accepts_nested_attributes_for
, then maybe this would work. I don't know what build_tape
is supposed to do, but the following will get you an array of tape_ids to work with:
@tape_ids = params[:run][:tapes].map { |k, v| v["tape_id"].to_i }
要完成关联,您可以执行以下操作
To complete the association, you could do something like
params[:run][:tapes].each do |k, v|
t = Tape.find(v["tape_id"].to_i)
t.run = @run
t.save
end
这篇关于访问params []值内的参数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!