Topic: Looping through params keys

I'm a bit new to both Rails and Ruby so sorry if this is easy.

I have a form which has multiple "extra" fields like so:

c1, c2, c3 etc.

So I'd like to loop through the params hash to get each of these values, I tried.

params.each_index do |i|
   if i = /$c\d+^/
   ... create new model object.
   end
end

but each_index doesn't seem to work on params since its a "HashWithIndifferentAccess"

Anyone else have a way to do this.

Thanks!

Re: Looping through params keys

You can just do this:

params.each do |key, value|
  if key =~ /$c\d+^/
    #...
  end
end

However, I recommend giving your fields a name like this:

<%= text_field_tag 'c[]' %>
<%= text_field_tag 'c[]' %>
<%= text_field_tag 'c[]' %>

These values will be collected into an array in the params, so you can do this:

params[:c].each do |value|
  #...
end

Railscasts - Free Ruby on Rails Screencasts

Re: Looping through params keys

I would have gone the route you suggested, I've actually used that for a similar little app based on your other tutes, but in this app I'm given the format of the form request, I'm not building the form page.

One other question.  So I used your code like so:

      if key =~ /^c[0-9]+$/ 
        e = @log.log_extras.build
        e.c_key = key
        e.c_val = params[key]
      end
      if @log.save ....

Now this works but that confuses me, because it saves more than one value, where it seems that e should be getting overwritten each time so only one "log extra" should be saved.   Is there some secret Ruby sauce happening here? Also is there a cleaner way to implement this code?

I tried:

      if key =~ /^c[0-9]+$/ 
        @log.log_extras.build do |e|
          e.c_key = key
          e.c_val = params[key]
        end
      end

Which isn't really any cleaner but it seems more "Rubylike" ;-) also, How do you know if a method call has a callback block available to it?  And what it does?

Thanks for your help.

Last edited by bitdamaged (2006-11-16 20:16:43)