简体   繁体   中英

each loop in ruby not working

I have a very simple each loop written in Ruby :

params[:category].each do |i|
  cat = Category.find(i)
  string << cat.name
end

The strange issue is that it only ever runs through this loop once!

params[:category] should be an array of params that all came in under the category label, right?

this was generated using a select tag in the controller:

<%=select_tag "category", options_from_collection_for_select(@category,"id" , "name"),:multiple => true, :class=>"bbFormSelect",:id=>"select_category", :name => "category" %>

Let me know if you see what's wrong!

You can always inspect the content of a variable by manually logging it like this:

logger.info(params[:category])

That will work from all Controllers.

But I would recommend you to go by this in a different way. With your approach the controller will call the database once for every category supplied. It should be enough to send it to the find method like this:

@categories = Category.find(params[:category])
names = @categories.map(&:name).join

If the find method gets an array of ids instead of just an id, it will return an array of categories.

Use <%= debug params[:category] %> somewhere in your view to see what the contents of the posted params are. If the loop runs once, then there is one entry in the categories.

Other than that the loop seems fine (string should be initialized before, i suppose you have that since you get no error).

如果您希望Rails根据输入参数构建一个类别数组,请将输入的名称更改为category [],如下所示:

<%=select_tag "category", options_from_collection_for_select(@category,"id" , "name"),:multiple => true, :class=>"bbFormSelect",:id=>"select_category", :name => "category[]" %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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