Accessing array of parameters inside the params[] value

江枫思渺然 提交于 2019-12-08 05:27:18

问题


I have the following Parameters:

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 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 %> 

回答1:


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


来源:https://stackoverflow.com/questions/7783755/accessing-array-of-parameters-inside-the-params-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!