1

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!

2
  • ps. params[:category] will result in a length larger than 1, correctly. Commented Apr 8, 2011 at 1:30
  • What does string have, and what did you expect it to have? Commented Apr 8, 2011 at 1:48

3 Answers 3

6

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.

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

Comments

3

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).

Comments

1

If you want Rails to build you an array of categories from the input parameters, change the name of your input to be category[], like so:

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

Comments

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.