Adding a Drop-down List in Rails with a Foreign Key


Setting up a foreign key relationship in Rails is easy, however, the form for the relationship proved to be a bit tricky. Ideally, you want the foreign key to be selected if it’s set in the show view and you want it to save in the new and edit views. Here is how to make that happen.

I’ll start from scratch here. I’m assuming you have a shell open at the root of your Rails project. We’ll make two models that have a foreign key relationship. Any Address can have one state. Address has the UI, so use the scaffold generator. It doesn’t make much sense for State to have a UI, so just use the model generator. Obviously you could write these yourself as well.

Next we’ll want to add the states as a seed, so add this to seeds.rb in the db directory

To add the foreign key, add a belongs_to relationship in the Address migration in the db/migrate directory. It’ll look like this

Also add a belongs_to relationship to the Address model in app/models/address.rb

Once we run the migration and seed, the address table will have a column called state_id. The states table will have all the states from the seed. Back at the shell, run the migration and seed.

Now let’s add the UI bit for Address. Add this to the app/views/addresses/_form.html.erb. Note the form-control class is for Bootstrap. You can add whatever class you want.

Fire up the rails development server by typing rails s at the shell. Visit http://localhost:3000/addresses/new in the browser and it’ll look like this:

select1select2

Almost done! The state_id value won’t save unless you permit it in the Address controller. Go to the Address controller in app/controllers/addresses_controller.rb and add the properties to permit in the address_params method at the bottom.

Now you should be able to save and update Addresses with their associated State via the state_id column.


Advertisement

One Comment

Name
A name is required.
Email
An email is required.
Site
Invalid URL