Database and check
Model basics is here.
Topics
About database
About operations
Configuration file
config/database.yml
Example(Mac OS X)
# SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 production: adapter: sqlite3 database: db/production.sqlite3 pool: 5 timeout: 5000
SQLite3
You need gem
gem install sqlite3
MySQL
You need gem
gem install mysql2
Database setting detail
config/database.yml(Linux, Ubuntu)
development: adapter: mysql2 encoding: utf8 reconnect: false database: mysqltest_development pool: 5 username: root password: socket: /var/run/mysqld/mysqld.sock
Name | Description |
---|---|
adapter | Database server |
encode | Encoding |
reconnect | Whether we reconnect or not |
database | Database name |
pool | Maximum of connection pooling |
username | Username |
password | Password |
host | Hostname of database server |
socket | Socket for server |
See SQLite3
Use sqlite3 command(in application root)
sqlite3 db/development.sqlite3
After connecting, you can use SQL.
See table list
.tables
See table schema
.schema table_name
table_name is table name.
Exit
.exit
You can also use .quit to exit sqlite3
Add database data from rails console
rails console
You can see connector info
Loading development environment(Rails 4.0.2)
Create data example
Country.create(name:'Japan' population:10000000)
If you want to use new, some steps are required.
japan = Country.new japan.name = 'Japan' japan.population = 100000000 japan.new_record? # check new record or not? japan.save
Check in rails console
Check some data for testing(using rails console)
See first item
Country.first
See last item
Country.last
See all
Country.all
See class(database) definition
Country.first.class
See yaml style
puts Country.all.to_yaml
Get using each
Country.all.each do |country| puts country.name end