Forum: Ruby on Rails ordering of params

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2006-02-02 18:13
(Received via mailing list)
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 <br />
<%= text_field 'answer', 'email' %> Email <br />
......

# 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
230ccd9aa66613ac4515ff5861b4c5af?d=identicon&s=25 Gabe Boyer (Guest)
on 2006-02-02 21:30
(Received via mailing list)
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
This topic is locked and can not be replied to.