Ordering of params


#1

I have a few long forms. I want to email out the user’s response on the
form.

So I have something like:

View

<%= text_field ‘answer’, ‘name’ %> Name

<%= text_field ‘answer’, ‘email’ %> Email

Controller

def form_submit
answers = params[:answers]
email_text = “New form submission receieved”
answers.each do |question, answer|
email_text << “#{ question.humanize }: #{ answer }\n”
end

send email

end

However, I don’t iterate through the answers in the order that they
were in the form, the answers are retrieved from params in a random
order (since hashes aren’t ordered).

Is there any way to do something like this and keep a sensical order
to the email?

Thanks,
Joe


#2

I think this is kinda ugly, but it should do the trick:

QUESTION_ORDER = %w{ name email … }

def form_submit
answers = params[:answers].sort_by { |question, _|
QUESTION_ORDER.index(
question.to_s) }
email_text = “New form submission received”
answers.each do |question, answer|
email_text << “#{ question.humanize }: #{ answer }\n”
end
end

Gabe