In this post, we will see how to work with database. For that, we will create models, migrations and then migrate to create database tables.
First we should know what a model is. Models are Ruby classes that talk to database, store and validate data, perform business logic etc. They allow us to interact with database without using SQL queries. There are lot of pre-defined methods that helps in creating, updating, deleting and reading records from database and return them as objects. This makes developer’s life much easy.
Ruby also support relationship between models. For example, if you try to read employee object from database, you can also get sale object as well. We don’t have to write any table joins for this.
Let us create an example and see how models work. Here are the steps for this:
- Create a new rails project. Click here for how to.
- Now move into the project folder on command prompt.
- Next we will create a controller which will handle tasks for CRUD (Create, Read, Update, Delete) operations on employees. Execute the following command:
rails g controller employees create save list edit update destroy
- Since we do not need views for save, update and destroy methods, go ahead and remove the following files
app\views\employees\save.erb.html app\views\employees\update.erb.html app\views\employees\destroy.erb.html
- Now create a model for employee. Execute the following command:
rails generate model Employee
This will create a model class with no fields. The class would be located in:
app\db\migrate\xxx_create_employees.rb
- Open the above file and make it look like this:
class CreateEmployees < ActiveRecord::Migration def change create_table :employees do |t| t.string :name, limit: 50 t.string :gender, limit: 6 t.string :email, limit: 255 t.string :status, limit:20 t.timestamps null: false end add_index :employees, :email, unique: true end end
Rails automatically adds id, created_at and updated_at fields to the table, so we don’t have to mention here.
- Now, we will use SQLite database provided by default for this post. It is a file based database. You can use any other database of your choice but for now, let’s use SQLite.
- Open your command prompt and execute the following command from the project directory:
rake db:migrate
This will create the file db\development.sqlite3
- So, our database is ready now. Next we will put our CRUD logic in the employee controller. Here is the code for the employee controller:
class EmployeesController < ApplicationController def list @employees = Employee.all @found = !@employees.empty? end def create @employee = Employee.new end def save @employee = Employee.create(employee_params) # pass employee_params function if @employee.save redirect_to :action => 'list' else render :action => 'create' end end def destroy @employee = Employee.find params[:id] @employee.destroy redirect_to :action => 'list' end def edit @employee = Employee.find params[:id] end def update @employee = Employee.find params[:id] if @employee.update_attributes(employee_params) redirect_to :action => 'list' end end # this function specifies the fields to be used in mass assignment # older way of this was using 'attr_accessible' in model def employee_params params.require(:employee).permit(:name, :email, :gender) end end
- Next we need to update our views. Here is code for create.html.erb
<%= link_to 'All employees', :action => 'list' %> <br/><br/> <h1>New Employee</h1> <%= form_for @employee, :url => {:action => 'save'} do |f| %> <p> Name: <%= f.text_field 'name' %> </p> <p> Email: <%= f.text_field 'email' %> </p> <p> Gender: <label><%= f.radio_button 'gender', "Male", :checked => true %> Male</label> <label><%= f.radio_button 'gender', "Female" %> Female</label> </p> <p> <%= f.submit "Create" %> </p> <% end %>
- Here is the code for list.html.erb
<%= link_to 'New Employee', :action => 'create' %> <br/><br/> <% if @found %> <h1>Listing Employees</h1> <table> <tr> </tr> <% @employees.each do |employee| %> <tr> <td><%= employee.id %></td> <td><%= employee.name %></td> <td><%= employee.email %></td> <td><%= employee.gender %></td> <td><%= link_to 'Edit', :action => 'edit', :id => employee.id %></td> <td><%= link_to 'Delete', {:action => 'destroy', :id => employee.id}, :confirm => 'Are you sure to remove this employee?', :method => :post %></td> </tr> <% end %> </table> <br /> <% else %> No employees added <% end %>
- Here is the code for edit.html.erb
<h1>Edit employee</h1> <%= form_for @employee, :url => {:action => 'update', :id => @employee.id} do |f| %> <p> Name: <%= f.text_field 'name' %> </p> <p> Email: <%= f.text_field 'email' %> </p> <p> Gender: <label><%= f.radio_button 'gender', "Male", :checked => true %> Male</label> <label><%= f.radio_button 'gender', "Female" %> Female</label> </p> <p> <%= f.submit "Update" %> </p> <% end %>
- Finally, here are the entries in my config\routes.rb
get 'employees/create' post 'employees/save' get 'employees/list' get 'employees/edit' post 'employees/destroy' patch 'employees/update'
- Now you can start your server and execute the url:
http://localhost:3000/employees/list
That’s it from this post.
*****Good Post*****