开发者

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜