LoginSignup
57
55

More than 5 years have passed since last update.

Rails4で実戦的なブログを作成(その1)

Posted at

ブログアプリケーションの作成

ブログアプリケーションを作成します。
本記事ではシンプルにmyblogという名前にしておきます。どんな名前でもいいのですが、この後作成するモデル名と被ってしまうため、blogだけは避けてください。

$ rails new myblog

Gemfileの書き換え

今回はSqlite3ではなくPostgreSQLを使用するため、gem 'sqlite3'からgem 'pg'に書き換えます。

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.beta1'

gem 'pg'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 4.0.0.beta1'
  gem 'coffee-rails', '~> 4.0.0.beta1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', platforms: :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.0.1'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano', group: :development

# To use debugger
# gem 'debugger'

gemを変更したので、gemをインストールします。

$ bundle install

データベース設定の変更

自動生成したままだとSQLite3の設定になっているデータベースの設定を変更します。当面は開発にしか使わないので、developmentだけ作成しておきます。

config/database.yml
development:
  adapter: postgresql
  database: mydiary
  username: bloguser
  password: password
  host: localhost
  encoding: utf8
  pool: 5
  timeout: 5000

bloguserユーザにデータベース作成権限を与えておいたので、rake dbコマンドでデータベースを作成します。

$ rake db:create

ブログ(Blog)モデルを作成する

まずはじめにブログ(Blog)モデルを作成します。

$ rails g scaffold Blog name:string
$ rake db:migrate

ここでは、名前(name)のみを持つように定義しておきます。

名前の入力を必須にする

名前を必須項目に設定します。

app/models/blog.rb
class Blog < ActiveRecord::Base
  validates_presence_of :name
end

ブログを追加する

サーバを起動し、ブログが追加できることを確認します。

57
55
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
55