Storing Data in a Relational Database in Rails
Working with database in Rails starts with the creation of your database and setting up connection from your app to it. In order to set up database connection, you need to open up your config/database.yml file and add connection information to it.
default: &default
adapter: postgre
host: localhost
username: sa
password: pass
development:
<<: *default
database dev_database
You can also find test: production: database sections in config/database/yaml file. These types of databases are used for different stages of your development process. Ruby on Rails sets development as your default database.
As long as you have development database connection set up, you are ready to start development with database tables. Creating database table is trivial task if you know RDBMS. Rails framework has one caveat that you may find strange if you dealt with RDBMS before. It requires you to name your tabled as pluralized nouns. ActiveRecord pluralization can be switched off with the help of the following line of code inside config/initializers/pluralization.rb file:
ActiveRecord::Base.pluralize_table_names = false
You can also add additional rules to pluralization engine by modifying config/initializers/pluralization.rb file. In fact, ActiveRecord relies on activesupport gem for pluralization rules and you can use activesupport outside of ActiveRecord if you need to.
Let’s imagine that we have database table called “cars” with primary key “car_id” and two fields “title” and “year”. This table can now be used by Rails in order to generate Car model. We do this by executing the following command line from the root of the application
.rails generate resource Car
This Car model is now accessible from all parts of your Ruby on Rails application including controllers, views, mailers, and helpers.
We can now start querying Car model with various conditions that allow us to retrieve information of interest from Cars database table. Here is an example of how you can retrieve 5 cars ordered by title and with the condition of make year equal to year of 2015.
Car.all( limit: 5, order: title, conditions: ‘year = 2015’).