lamrin
lamrin

Reputation: 1441

Rails create multiple records with multiple fields

I am trying to create multiple records with two collections that i have

View

<%= text_field_tag "user[]",'', :class=>"user_name" %>
    <%= radio_button_tag "is_checked[]", '1',false %><br>

    <%= text_field_tag "user[]",'', :class=>"user_name" %>
    <%= radio_button_tag "is_checked[]", '1',false %><br>

Controller

user = params[:user]

is_checked = params[:is_checked]

user.each do|a|

u = User.new

u.name = a

u.save

end

here, i want to know how to save the is_checked value along with name..

i getting the collection for both user and is_checked but i could able to loop only one..

please, guide me how to create multiple records with the two fields

thanks

Upvotes: 1

Views: 4080

Answers (1)

Staelen
Staelen

Reputation: 7841

you might want to do it this way instead:

View:

<% 1.upto(2) do |i| %>
  <%= text_field_tag "fields[#{i}][user]",'', :class => "user_name" %>
  <%= radio_button_tag "fields[#{i}][is_checked]", '1', false %><br>
<% end %>

so you will receive something like this:

"fields" => {
  "1" => {"user" => "value of 1", "is_checked" => "for 1"},
  "2" => {"user" => "value of 2", "is_checked" => "for 2"}
}

then you can do this in the Controller:

params[:fields].each do |i, values| do
  # where i is the i-th set
  # and values are the user inputs

  u = User.create(values)
end

hope this helps! =)

Upvotes: 6

Related Questions