Populating form values through a link in Rails
Today I was asked to help with creating a link on a website that should take the user to a different page where a form should be filled out based on paramaters supplied through the link URL.
Rather than writing a long email response I wrote a little example app and this blog post. (If you’re just after the code you can find it on my github site.)
For this example I’m going to create a page with 3 links, each link will take you to the same page but fill out a form on the target page with different values. The first thing I’m going to do is to create the page that contains the links.
We start off by adding the route (config/routes.rb):
Now I simply need to add the WelcomeController and add the index view (app/views/welcome/index.html.erb),
The view I’m leaving blank for now. Now if you navigate to the root of our appliation (in my case http://localhost:3000) you should get a blank page. (If you get the familiar Rails welcome page you need to remove the public page at public/index.html)
Ok, so where are we going to link to? Since we want to pass parameters through the link I am going to setup a rails route that contains two parameters.
If some of this syntax seems strange to you take a look at my post on Routing in Rails 3.
I now have a route, but I’m not using it in the page. So let’s modify the view that I left blank (app/views/welcome/index.html.erb).
Now we have the links, but they’re not going anywhere. We’ve told the route what controller to use (SignupController), but we haven’t defined that controller.
This is the most important part. We’ve defined two variables in our route (name and value) which will be passed to our controller through the params hash. I now need to assign these two variables as attributes to make them available to the view.
The last step is to create the view (app/views/signup/new.html.erb) and set the variables in the form.
And that’s all we need! When you click the different links you get a form populated by the parameters we specified in the link.
You can find the example application on my github site. Happy coding.