1

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

1 Answer 1

6

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! =)

Sign up to request clarification or add additional context in comments.

4 Comments

I have a doubt u = User.create(values) you are looping this that means that much insert query will be executed. How can combine that into a single insert query. I am stuck with this. Any ideas about this..
unfortunately, u can't really do a bulk insert in a single insert query. however, you can make use of transaction so that ActiveRecord will not keep closing and opening transactions. alternatively, you can do raw sql, but i'll still stick to ActiveRecord as much as i can =)
@Staelen Hey, i have a little question for you. How do you check and display errors for so many objects of one type?
@ExiRe can you elaborate more? do you mean ActiveRecord objects? if so, then you can try to read up on ActiveRecord::Errors, if you are talking about forms, then you've got to use javascript to handle form checking =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.