简体   繁体   English

循环遍历一个复选框数组列表,在控制器中的rails 3.1上的ruby中插入多条记录

[英]Looping through a list of checkboxes array to insert multiple record in ruby on rails 3.1 in controller

I have a list of check boxes created with check_box_tag ( <%= check_box_tag "user_ids[]", user.id %> ). 我有一个使用check_box_tag创建的复选框列表( <%= check_box_tag "user_ids[]", user.id %> )。 Now i want to loop through all the check-boxes based on users_ids in controller and insert data of all the users selected. 现在我想基于控制器中的users_ids循环遍历所有复选框,并插入所有选定用户的数据。

As Meltemi says, the usual way to iterate in ruby is .each . 正如Meltemi所说,迭代ruby的常用方法是.each In your case, probably something like this, in the controller that receives the form: 在你的情况下,可能是这样的,在接收表单的控制器中:

params[:user_ids].each do |user_id|
  u = User.find(user_id)
  u.do_something_to_that_user  #call a method or some such on the user
  something_else.users << u    #associate that user with something else
end

Alternatively, it can often be more efficient to do all of this in one go, though the exact form thereof depends on what you're doing with the user. 或者,一次性完成所有这些操作通常更有效,但其确切形式取决于您对用户所做的事情。 For instance, if you want to associate the checked users with some record: 例如,如果要将选中的用户与某些记录相关联:

Record.user_ids = params[:user_ids]

Or if you want to update all of those users in some way: 或者,如果您想以某种方式更新所有这些用户:

User.where(:id => params[:user_id]).update_all(:attribute => some_value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM