Get an array from a Rails form

I need to create a form for an account resource. In this form I need to collect some set of identifiers as an array in the params hash in the relationships attribute.

So, the final params[account] hash from the POST request should look like this:

 {:name => 'somename', :relationships => ["123", "23", "23445"]} 

How do I create form_for fields? I tried this but did not work:

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

The number of elements in @eligible_parents changes each time.

relationships is neither an association nor an attribute in the account model.

I need to use virtual attributes, but I need to fill an array from the form.

Please, help. How can i do this?

+6
source share
3 answers

You still need fields_for , just use :relationships as 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

+5
source

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

 <%= f.check_box "relationships", nil, :value => p.id, :name => "relationships[]" %> 
+2
source

I found this in the cleanest way ...

If you are working with direct 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 be returned as follows:

 "team" => { "people" => [ {"first_name" => "Michael", "last_name" => "Jordan"}, {"first_name" => "Steve", "last_name" => "Jobs"}, {"first_name" => "Barack", "last_name" => "Obama"} ] } 
+2
source

Source: https://habr.com/ru/post/907741/


All Articles