Get an array from a Rails form

后端 未结 5 1223
野趣味
野趣味 2021-01-12 13:10

I need to design a form for a account resource. In that form, i need to collect some set of ids as an array in the params hash in attribute called

相关标签:
5条回答
  • 2021-01-12 14:00

    I found this to be the cleanest way...

    If you are working with straight data and want to send back an array without using any of these @objects:

    <%= form_for :team do |t| %>
      <%= t.fields_for 'people[]', [] do |p| %>
        First Name: <%= p.text_field :first_name %>
        Last Name: <%= p.text_field :last_name %>
      <% end %>
    <% end %>
    

    your params data should return like this:

    "team" => {
      "people" => [
        {"first_name" => "Michael", "last_name" => "Jordan"},
        {"first_name" => "Steve", "last_name" => "Jobs"},
        {"first_name" => "Barack", "last_name" => "Obama"}
      ]
    }
    
    0 讨论(0)
  • 2021-01-12 14:01

    In a complex form, with nested attributes, you can make use of the f.object_name helper. But beware of the syntax when doing interpolation. This is correct:

    "#{f.object_name}[relationships][]"
    

    This is NOT correct:

    "#{f.object_name}[relationships[]]"
    

    It always trips me up.

    0 讨论(0)
  • 2021-01-12 14:07

    I'm working in something similar. My issue was how to pass the input name to a partial to resolve it as a hash using the rails form_for helper.

    So, my solutions was something like this:

    = render 'my_partial', form: form, name: "item_ids[item.id]"

    So, this gonna render an html like this:

    <input class="form-control" name="products[items_ids[1]]" id="products_items_ids[1]">

    The number 1 is the item.id, this is how HTML understand that you gonna pass an array or hash, all depends your config.

    So, the params gonna look like this:

    "items_ids"=>{"1"=>"1"}

    This is working for me with an form_object + virtus

    0 讨论(0)
  • 2021-01-12 14:10

    If you want to send array of values just use [] in name attributes.In your case just use

    <%= f.check_box "relationships", {}, :value => p.id, :name => "relationships[]"   %>
    
    0 讨论(0)
  • 2021-01-12 14:13

    You still need a fields_for in your view, just use :relationships as the record_name then provide an object.

    <%= form_for @account do |f| %>
        <%= f.text_field :name %>
    
        <% fields_for :relationships, @eligible_parents do |p| %>
            <%= p.check_box "relationships", nil, :value => p.object.id  %>
            <b><%= p.object.name %></b><br/>
        <% end %>
    
        <%= f.submit "Submit" %>
    <% end %>
    

    Documentation here: ActionView::Helpers::FormHelper

    0 讨论(0)
提交回复
热议问题