Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Forms on the Same Page with Rails

So I'm building a rails app for high school students and I've hit a problem when it comes to creating users.

I want the students to only be able to create accounts if they select their school and type in their school's password correctly.

What is the correct / easiest way of doing this? Should I create a gatekeeper to the user#new action that they have to pass first or if their a way that on the same page a student can submit to forms. One would be the regular username, email, password using:

form_for @user do
  ...
end

But then creating another form for the high-school / high-school password selection.

Ideally the controller would be able to get the params of the high-school form, validate those, then go on to create the user from the user params.

Is this possible using rails?

My setup: Rails 3 and Ruby 1.9.2dev

Thank you!

like image 930
Eric Koslow Avatar asked Mar 20 '10 03:03

Eric Koslow


2 Answers

You can do this with fields_for (http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for)

Your view will look something like

form_for @user do |f|
  fields_for @school do |school|
    school.text_field     :name
    school.password_field :password
  end

  f.text_field     :username
  f.text_field     :email
  f.password_field :password
  f.submit "Submit"
end

Then in your controller, params[:user] will represent the user data, and params[:school] will represent the school name/password.

You can then validate the correct school password before creating the user.

like image 196
jrallison Avatar answered Sep 29 '22 00:09

jrallison


jrallison is right about fields_for, but I would suggest considering whether it's strictly necessary to do both on the same form.

What you're describing with the school name and password sounds a lot like user authentication. It might not be a "user" in the sense of a single person, but in this case the "user" is the school. Maybe you should treat it that way: have a separate login form, create a session if they succeed (so that they won't have to type their school's password over and over again later on), and do the standard flash messages and such if they fail.

At that point, the form you need is simple and single-model. And if other features become necessary later on that also need the school password, you're already a step ahead.

like image 29
SFEley Avatar answered Sep 29 '22 00:09

SFEley