Rubyのversionはruby 2.0.0p247
RailsのversionはRails 4.0.0を使う。
分からなかったらRailsGuideを見る。
データベースはMysqlを選ぶ
>rails new pakon(アプリの名前は好きなのでOK) -d mysql
ここで開発フォルダをpakonと命名。
データベースはsqliteがデフォルトなのでそれをmysqlにするにはオプションで-dをつける
>rails g controller articles(コントローラー名) --skip-assets
> 下記作られるファイル
create app/controllers/articles_controller.rb
invoke erb
create app/views/articles
invoke test_unit
create test/controllers/articles_controller_test.rb
invoke helper
create app/helpers/articles_helper.rb
invoke test_unit
create test/helpers/articles_helper_test.rb
--skip-assetsはjs,cssファイルをつくるのをキャンセルする意味。
必要ないので削除。
コントローラー名は複数形にするのが基本、articleではなくarticlesで、、、、
コマンド入力に失敗したならrails d controller article(コントローラー名)でコマンドを入力、削除する。
viewのファイルも自動で作られるので便利。
>rails g model article name:string title:string content:text
> 下記作られるファイル
invoke active_record
create db/migrate/20130907012228_create_articles.rb
create app/models/article.rb
invoke test_unit
create test/models/article_test.rb
create test/fixtures/articles.yml
もし失敗したなら gのところをdにする、二番と同じ
モデル名は単数形にすること
> rake db:create
> rake db:migrate
rake db:createはデータベースを作る、rake db:migrateはデータベースにカラムを追加したり、削除したりする時に使う。migrationの機能がある事によってMySQLでもSQliteでも同じコマンドでデータベースの変更が打てるので便利。SQliteの場合rake db:createは打たなくもOK。
ちなみにカラムはデータの種類を表すもの。
nameというカラムにstringという文字列をいれる型を設定
textは長い文字列。
サーバーを起動
> rails s
rails serverでも打てるが省略
ターミナルに下記の情報がでる
Rails 4.0.0 application starting in development on http://0.0.0.0:3000
http://0.0.0.0:3000 に接続して確認する。
Welcome aboardの文字画面とRailsのロゴが入ったページに移動したら成功。
pakon/app/controller/articles_cotroller.rbのファイルを開く。
以下のコードを追加。
class ArticlesController < ApplicationController
# ページに表示一覧
def index
@article = Article.order("created_at DESC")
end
# ページの詳細
def show
@article = Article.find(params[:id])
end
# データの新規作成のオブジェクトを作る
def new
@article = Article.new
end
# データベースに新規作成のデータをセーブ
def create
@article = Article.new article_params
if @article.save
redirect_to :root
flash.notice = "作成できました!"
else
render action: :new
end
end
# 更新するデータを取得する
def edit
@article = Article.find(params[:id])
end
# データを更新する
def update
@article = Article.find(params[:id])
if @article.update_attributes article_params
redirect_to :root
flash.alert = "更新しました!"
else
render action: :edit
end
end
# データを削除する
def destroy
@article = Article.find(params[:id])
if @article.destroy
redirect_to :root
end
end
private
def article_params
params.require(:article).permit(
:title,
:name,
:content
)
end
end
indexアクションはデータベースから作成日時が新しい順にデータをとってくる。
DESCは降順、ASCは昇順。
showアクションはparamsという命令パラメータのデータを取得する。
newアクションは新規データのオブジェクトの作る。
createアクションは新規のデータをsaveする、データベースに追加する。
editアクションは更新するデータを取得する。
updateアクションはデータを更新する。
update_attributesは複数の項目を一度に変更・保存するメソッド
deleteアクションはデータを削除する。
privateの下にあるメソッドはRails4から導入されたStrong Parametersという機能。
articleモデルの中にあるtitle、name、contentのカラム指定している。
これをどれか入れ忘れるとデータがデータベースに入らないので注意。
updateのメソッドで使っている。
createメソッドとupdateメソッドにあるflashメソッドは簡単な通知を出したい時に便利。
コントローラーで定義してviewsフォルダにあるファイルに<%= flash.notice%>を書いて表示する。
views/articles/index.html.erbを参考
pakon/app/view/のフォルダの下にファイルを作る
・index.html.erb
・show.html.erb
・new.html.erb
・edit.html.erb
・_form.html.erb
html.のあとにerbつけることによってhtmlのファイルにRubyのコードを埋め込めるようになる
<% %> => Rubyの命令を実行する。
<%= %> => Rubyの命令を実行し、Htmlファイルに出力。
<%# %> => コメントアウト
などがある。
_form.html.erbはファイル名の名前にアンダスコア(_)を付ける事によってviewのテンプレートに部品みたいな感じで埋め込む事ができる。共通したコードを管理する時に便利。詳細はnew.html.erb、edit.html.erb、 _form.html.erbのコードを参照。
# index.html.erbを編集
<%= link_to "新規作成", new_article_path %>
<%= flash.notice %>
<%= flash.alert %>
<hr>
<% @article.each do |f| %>
<ul>
タイトル:<%= link_to f.title, article_path(f)%>
</ul>
<ul>
名前:<%= f.name %>
</ul>
<ul><br>本文:</br>
<%= simple_format(truncate(f.content,:length => 1000)) %>
</ul>
<ul>
作成日時:<%= f.created_at.strftime("%Y/%m月%d日(#{%w(日 月 火 水 木 金 土 日)[Time.now.wday]})") %>
</ul>
<ul>
<%= link_to "編集", edit_article_path(f) %> : <%= link_to "削除", f,
:confirm => "削除してよろしいですか?",
:method => :delete %>
</ul>
<hr>
<% end %>
simple_formatはtextareaに改行付きで入力した時にp とか br をいれて HTML として表示する。
これを使うときれいに表示される。
truncateは一覧画面等に収まらない長い文字列を表示する時に便利。lengthで指定して表示する。
# show.html.erbの編集
<%= link_to '記事一覧に戻る', :articles %>
<hr>
<ul>タイトル:<%= @article.title %></ul>
<ul><br>本文</br><%= simple_format(@article.content) %></ul>
<ul>作成日:<%= @article.updated_at.strftime("%Y/%m月%d日(#{%w(日 月 火 水 木 金 土 日)[Time.now.wday]})") %></ul>
#new.html.erbの編集
<%= link_to '前に戻る', :articles %>
<hr>
<%= form_for @article do |f| %>
<%= render "form", f: f %>
<p><%= f.submit %></p>
<% end %>
アンダースコアで(_)でファイル名を付ける事によってrenderという命令でファイルを読み込めるようになる。
#edit.html.erbの編集
<%= link_to '前に戻る', :articles %>
<hr>
<%= form_for @article do |f| %>
<%= render "form", f: f %>
<p><%= f.submit %></p>
<% end %>
#_form.html.erb
<% if @article.errors.any? %>
<h2>エラーが<%= (@article.errors.count) %>件あります</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<table>
<tr>
<th><%= f.label :title %></th>
<td><%= f.text_field :title, size: 50 %></td>
</tr>
<tr>
<th><%= f.label :name %></th>
<td><%= f.text_field :name, size: 50 %></td>
</tr>
<tr>
<th><%= f.label :content %></th>
<td><%= f.text_area :content, :cols => 70, :rows => 20 %></td>
</tr>
</table>
pakon/app/models/article.rbのファイルを開く
以下のコードを追加
class Article < ActiveRecord::Base
validates :title, presence: true
validates :name, presence: true,:length => { :maximum => 20 }
validates :content, presence: true
end
モデルにバリデーションを追加する。
バリデーションはデータをsaveする時に制約をつける機能。
・Titleは必須入力
・Nameは必須入力かつ入力できる文字が20字以内
・Contentは必須入力
初期のデータベースはなにもデータが入ってない状態なのでデータを作る
pakon/db/seeds.rbを開く
class Array
def choice
at( rand( size ) )
end
end
def kuman(size)
[*0..9, *'a'..'z', *'A'..'Z'].sample(size).join
end
1.upto(50) do |abc|
Article.create(
{ name: ['gorira', 'koara', 'pantu', 'women'].choice,
title: [kuman(5), kuman(6), kuman(10), kuman(7)].choice,
content: ( kuman(100) + "\n" ) * 10
})
end
下記のコマンド打ってデータベースにデータを挿入
>rake db:seed
ルート設定しなきゃページが読み込まれないからルートを設定する、
ルートはページの住所みたいなもの
pakon/config/routes.rbを開く
Pakon::Application.routes.draw do
root 'articles#index'
resources :articles
end
root 'article#index'はサイトに接続して最初に開かれるページを設定する。
コントローラー名のあとにアクション名を書いて指定。