参考にしたのはhttp://guides.rubyonrails.org/getting_started.html
全て英文なのでかなり時間がかかった…。
とりあえず、controllerやview、dbなどの関係性や基本機能をサラッと学べるのでオススメ。長いので前後編にわけたぴょん。
早速、コマンドで以下を打つ。
rails new blog
cd blog
rails server
初めてrails serverを打った時のエラー処理については以下参照推奨。
http://qiita.com/htk_jp/items/1100a04f45151c928378
一度exitしてMac上で操作します。
ディレクトリをFinderで見れると便利なので設定する。というか、見れないとひたすらcdしていくことになる。。。w
sshfs vagrant@192.168.33.56:/home/vagrant/blog ~/blog
http://qiita.com/htk_jp/items/ec140f2492cab8e959d9
今回はディレクトリ名をblogにしたので、~/blogとなってます。
blogディレクトリに入ってから下のコマンドです。
rails generate controller welcome index
まずはインデックス(始めに表示されるページ)を作る。
app/views/welcome/index.html.erbを編集。
<h1>Hello,Rails</h1>
インデッスページが出来たので、ルートを設定する。
config/routes.rb に以下を追加。
root 'welcome#index'
192.168.33.56:3000で確認。※各自のローカルホスト:3000で確認。
CTR+Cで終了
また、ルートをいじっていく。
config/routes.rb
Blog::Application.routes.draw do
resources :articles
root 'welcome#index'
end
コマンドでルートを確認する。
rake routes
Prefix Verb URI Pattern Controller#Action
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET /
rails s
192.168.33.56:3000/articles/new
ROUTING ERRORエラーがでたので一度止める。
CTR+C
アーティクルのコントローラーを作成する。
rails g controller articles
rails sで立ち上げ
192.168.33.56:3000/articles/new
The action 'new' could not be found for ArticlesControllerというエラーがでる。
app/controllers/articles_controller.rbを追加
def new
end
rails s
192.168.33.56:3000/articles/new
Template is missing
Missing template articles/new, application/new with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: * "/home/vagrant/blog/app/views"
というエラーが出た。
app/views/articles/new.html.erbを作成する
<h1>New Article</h1>
192.168.33.56:3000/articles/new
表示された。
テキストフィールドとテキストエリアを作成してサブミットボタンをつける。
<h1>New Ariticle</h1>
<%= form_for :article do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :title %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
ブラウザを再読み込みすると出来てる。
サブミットボタンを押した時に移動する為のコードを書く。
<%= form_for :article, url: articles_path do |f| %>
サブミットボタンを押してみるとまたエラー…
Unknown action
The action 'create' could not be found for ArticlesController
createが見つかりませんってことなので、articles_controllerにcreateを作ってやる。
class ArticlesController < ApplicationController
def new
end
def create
end
end
こんな感じ。
実はこれだけだとまたテンプレートミッシングっていうエラーが出る。
def create
render plain: params[:article].inspect
end
んで、何も入力せずにボタンを押すと
{"title"=>"", "text"=>""}
こうなる。ちゃんとデータを受け取ってるのがわかる。
実は渡されたパラメータを見れているだけなので、モデルやらを追加していく。
rails generate model Article title:string text:text
次にarticles_controller.rbを次のように編集する。
class ArticlesController < ApplicationController
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
これで実行すると
Unknown action
The action 'show' could not be found for ArticlesController
というエラーが出た。showを作れってことみたい。
rake routes
article GET /articles/:id(.:format) articles#show
ほうほう。ではapp/controllers/articles_controller.rbに追加しましょう。
def show
@article = Article.find(params[:id])
end
では、app/views/articles/show.html.erbを作成。
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
これで、タイトルとテキストを入力してサブミットを押すと成功するはず。
このとき、アドレスがサブミットした回数で増加していってる。
次は一覧を作ってみる。
app/controllers/articles_controller.rbに次を追加。
def index
@articles = Article.all
end
追加したアクションの為のビューを作っていく。
app/views/articles/index.html.erbを作成する。
<h1>Listing articles</h1>
<table>
<tr>
<th>Title</th>
<th>Text</th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
</tr>
<% end %>
</table>
これで下にアクセスすると一覧が表示されるはず。
192.168.33.56:3000/articles
できた。
次は一覧にリンクを付けていく。
app/views/welcome/index.html.erbに追加。
<h1>Hello, Rails!</h1>
<%= link_to 'My Blog', controller:'articles' %>
<%= link_to 'New article', new_article_path %>
次はapp/views/articles/new.html.erbに戻るボタンを付ける。
<%= link_to 'Back', articles_path %>
showにも戻るボタンつけよう。
<%= link_to 'Back', articles_path %>
次はTitle入力欄にバリデーションを追加する。
※バリデーションとは入力文字数の制限をしたり、ルールを付ける機能
app/models/article.rbを編集。
class Article < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
end
これで5文字以下だと入力できなくなる。でも、エラーメッセージが出た方が便利なのでそれをやっていく。
app/controllers/articles_controller.rbを編集。
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
これでエラーの時は入力画面を再度表示するようにできた。次はエラーメッセージを出す。
app/views/articles/new.html.erbを編集。
<%= form_for :article, url: articles_path do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
これで完了。Titleを空欄でsubmitするとエラーメッセージが出ているのがわかる。
次からはEdit機能を追加していく。
def edit
@article = Article.find(params[:id])
end
次は追加したeditのファイルを作る。
app/views/articles/edit.html.erbを作成。
<h1>Editing article</h1>
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
<% if @article.errors.any? %>
<div id = "error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
次はupdate機能を追加。
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
そして、editとupdateのリンクをindexに追加する。
app/views/articles/index.html.erbを編集。
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="2"></th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
</tr>
<% end %>
</table>
showのページにもEditボタンを追加。
app/views/articles/show.html.erb
<%= link_to 'Back', articles_path %>
| <%= link_to 'Edit', edit_article_path(@article) %>
RubyのDon't repeat yourselfの観点から、まとめられるコードをまとめる。
new.html.erbとedit.html.erbのコードをまとめる。
app/views/articles/_form.html.erbを作成する。
<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id = "error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
ではこれをnewとeditに適用していく。
app/views/articles/new.html.erbを編集。
<h1>New article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
app/views/articles/edit.html.erbを編集。
<h1>Edit article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
次はデリート機能を追加する。
app/controllers/articles_controller.rbを編集。
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
インデックスにリダイレクトしているので、ビューを作成する必要はない。
次はインデックスにリンクをつける。
app/views/articles/index.html.erbを編集する。
<h1>Listing Articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="3"></th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
これで基本的な機能はできた。
すごく単純だが、CRUDの全ての機能をつけたことになる。
※CRUDとはCreate,Read,Update,Deleteのことで、webサービスの基本機能。