views:

5926

answers:

4

In reference to this

I've created a question in a webform like this:

<div class="form_row">
        <label for="features[]">Features:</label>
        <% [ 'scenarios', 'role_profiles', 'private_messages', 'polls' ].each do |feature| %>
          <br><%= check_box_tag 'features[]', feature,
                  (params[:features] || {}).include?(feature) %>
        <% end %>
</div>

So if scenarios and private_messages gets checked and I print out params[:features] I will get: scenariosprivate_messages

I was wondering how would I be able to obtain scenarios and private_messages separately from params. Is the mapping params[:features] = "scenariosprivate_messages" or is it really params[features] = ["scenarios", "private_messages"] ? If it's the latter how can I loop through them?

I write in my view:

<%= params[:features].each {|param|
    param.capitalize
} %>

and I still just get scenariosprivate_messages printed.

A: 

According to this blog post you should be able to access them individually as params[:features]['scenarios'] etc. Looping should just work like with all other arrays -- eg

params[:features].each { |param|
# do something with param
}

schweerelos
Hmmm it doesn't seem to work.
alamodey
Sorry, didn't realise you want to loop over it in the *view*. Just like Jim says, you should most likely not use params in your view.
schweerelos
+4  A: 

You shouldn't be using params in your views. You're best off assigning params[:features] to an instance variable in your controller and then iterating over that in your view.

But to answer your question, you're putting the equals sign for output in the wrong place. You want to output each element of the array individually instead of outputting the result of the loop.

Jim Puls
Why is this? «You shouldn't be using params in your views»
Júlio Santos
+9  A: 

Try this instead:

<% params[:features].each do |param| %>
  <%= param.capitalize %>
<% end %>

The problem with your original solution is that you're printing out the result of the block, which is the array itself, rather than printing out each element of the array.

Sarah Mei
+2  A: 

You must use humanize:

<% params[:features].each do |param| %>
  <%= param.humanize %>
<% end %>
vladr
Thanks. Neat function.
alamodey