Sometimes after performing scaffold or before scaffold in rails it’s become cumbersome that how to add drop-down in my scaffold. In this post we’ll learn how to do it within few steps.

Assume you have one model named “User” and another as scaffold named “Blog”. In model you have some predefined data with you.

Put some pre-define data in Seeds.rb file (for users)

User.create([
  {name: "Adam"},
  {name: "John"},
  {name: "Kapil"}
])

Generate model first

rails generate model User name:string

Now Generate scaffold

rails generate scaffold Blog title:string content:text user:references

Here “user:references” act as a foreign_key which resides in your migration file looks something like this

" t.references :user, index: true, foreign_key: true "

Besides that you can see one more change in models/user.rb file which looks something like this

 class Blog < ActiveRecord::Base
   belongs_to :user
 end

Now perform migration for both scaffold as well as for seed file like this

rake db:migrate
rake db:seed

As have used the scaffolding to generate our views so the example code for blog resides in _form.html.erb file of blog folder.

The code used to create the drop down list is:

<%= f.collection_select(:user_id, User.all, :id, :name, {:prompt => 'Select the user'}, :selected => @blog.user_id ) %>
  • :user_id is the foreign key that resides in the Blog table
  • User.all specifies which records to include in the drop down list
  • :id is the primary key in the User table
  • :name is the field from the Users table to display in the drop down list

That’s it. Now you are ready to use drop-down in your application.

Advertisements