Reputation: 67087
Say I've got that application that stores it's settings in a database.
For modifying settings, I just print each setting into a form using slim:
Sinatra part:
get '/settings' do
@settings = Setting.all
slim :showsettings
end
Slim part:
@@ showsettings
h1 Settings
form action="/settings" method="POST"
table
- @settings.each do |setting|
tr
td
label for="#{setting.name}" #{setting.name}
td
input type="text" name="#{setting.name}" value="#{setting.value}"
input.button type="submit" value="Update Settings"
When I submit the form, I get back to /settings
and want to process the POST request. I know that all of the parameters are stored in the params
variable.
If I print params, I receive the following string:
["name1", "value1"]["name2", "value2"]["name3", "value3"]["name4", "value4"]
How do I process all of the submitted parameters when I don't know how they are named? Of course, I could hard-code the parameter names into the code but this would be hard to maintain.
Edit:
What I'm basically looking for is something like the keys
function in Perl which I could use for something like for my $key ( keys %hash )
...
Upvotes: 0
Views: 283
Reputation: 79743
You can iterate over the entries in a Hash directly with each
, you don’t necessarily need to use keys
:
post '/settings' do
params.each do |key, value|
Setting.get(key).update(:value => value)
end
end
Upvotes: 2
Reputation: 67087
Found it myself:
post '/settings' do
params.keys.each do |key|
s = Setting.get(key)
s.update( :value => params[key])
end
end
Upvotes: 1