Jerome
Jerome

Reputation: 6189

Syntax for handling parameters dynamically

A series of parameters are being submitted to a Rails controller:

"25"=>"true", "30"=>"false", "35"=>"true", "40"=>"true", "45"=>"true", "50"=>"true", "55"=>"true", "60"=>"true", "65"=>"false", "70"=>"true", "75"=>"true", "80"=>"false", "100"=>"true"

The goal is to loop through:

@age_limits = [25,30,35,40,45,50,55,60,65,70,75,80,100]

and process based on each param's value.

The problem is that the syntax for referring to the param is evading me:

@age_limits.each do |limit|
  puts params[:"#{limit}"]
  if params[:"#{limit}"] == "true"
    session[:demographic_agegroups] << params[:"#{limit}"]
    puts session[:demographic_agegroups]
  end
end

Both params[:"#{limit}"] and params[":#{limit}"] do not allow to access the parameter. The former will return the value by putting into console (editor BBEdit does not consider it properly formed Ruby), but will not allow to process in its basis.

How can the controller properly access the param and process based on its value?

Upvotes: 2

Views: 135

Answers (1)

7urkm3n
7urkm3n

Reputation: 6311

You'r missing to convert int to string.

Since your params keys are string, you can use params[limit.to_s].

Also, if its key based "keyX".to_sym would be :keyX

Upvotes: 2

Related Questions