1
votes

At the moment I have a form_tag which contains inputs and puts these inputs into parameters. I want to be able to loop over them in the controller action.

I've tried getting all params excluding all the usual params (action, controller, model name etc.) and then using a wildcard like params[:prop*].

Here is the offending form inputs:

%input{:name => "userEmails", :id =>"userEmails", :type => "hidden", :value => ""}
  -@all_properties.each do |prop|
    %input{:name => "prop"+prop.name+"checkbox", :type => "checkbox", :id => "prop"+prop.name+"checkbox"}
    #{prop.name}
    %input{:name => "prop"+prop.name, :type => "text", :id => "prop"+prop.name}

These show up in params like {"propProperty1checkbox"=>"on", "propProperty1" => "testing", "propAnotherPropertycheckbox" => "on", "propAnotherProperty" => "another test value"} etc.

I'm unsure how to access these as the names of the properties can change and so need to be accessed abstractly.

2

2 Answers

1
votes

You can use #select on params hash to filter only the params that are interesting for you:

params = {"user_id"=>1, 
 "propProperty1checkbox"=>"on",                                                                                   
 "propProperty1"=>"testing",                                                                                      
 "propAnotherPropertycheckbox"=>"on",                                                                             
 "propAnotherProperty"=>"another test value"
}
params.to_h.select{|key, value| key =~ /^prop/}
#=> {"propProperty1checkbox"=>"on",
#"propProperty1"=>"testing",
#"propAnotherPropertycheckbox"=>"on",
#"propAnotherProperty"=>"another test value"}

EDIT

Example from the comment:

[13] pry(main)> {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"xxxxx", "userEmails"=>"[email protected],[email protected],[email protected],[email protected]", "propProperty1checkbox"=>"on", "propProperty1"=>"3", "propAnotherPropertycheckbox"=>"on", "propAnotherProperty"=>"4", "commit"=>"Submit", "Application"=>"8", "Company"=>"1" }.to_h.select{|k, v| k =~ /^prop/}
=> {"propProperty1checkbox"=>"on",
 "propProperty1"=>"3",
 "propAnotherPropertycheckbox"=>"on",
 "propAnotherProperty"=>"4"}
1
votes

You can try something like:

input(name: "props[#{pro_name}][checkbox]"...)
input(name: "props[#{pro_name}][text]"...)

Then, in your controller:

def method
  props = params[:props]
  props.each do |property_name, values|
    chk = values[:checkbox]
    text = values[:text]
  end
end