Skip to content

Instantly share code, notes, and snippets.

@ttakuya50
Last active August 29, 2015 14:07
Show Gist options
  • Save ttakuya50/ae7b274f49f5b759367b to your computer and use it in GitHub Desktop.
Save ttakuya50/ae7b274f49f5b759367b to your computer and use it in GitHub Desktop.
SWAFS October#3 - Ruby on Rails

#目標:認証付きTodoアプリ作成 とりあえず作ってみよう

##プロジェクトの作成

$rails new Todo
$cd Todo

##トップページの作成 トップコントローラとindexのビューを生成する。
$rails g controller top index

indexの編集

$vim app/views/top/index.html.erb  
//以下を追加
<h1>トップページ</h1>

次にルーティングを設定する

$vim config/routes.rb
//以下を追加
root to: "top#index"

サーバー起動

rails s

以下にアクセスするとトップページが出現するはず
http://localhost:3000/

##ユーザー新規登録の部分を作る

$vim Gemfile

次の箇所をコメントアウトを外し、bundleをインストール

$vim Gemfile
//コメントアウト外す
gem ‘bcrypt-ruby’, ‘~> 3.1.7’
$bundle install

次にユーザー情報を格納するテーブルを作成

$rails g model user name:string password_digest:string
$rake db:migrate

app/models/user.rbを編集
$vim app/models/user.rb

class User < ActiveRecord::Base
  has_secure_password
end

usersコントローラーを作成
$rails g controller users

/app/controllers/users_controller.rbを編集

$vim app/controllers/users_controller.rb

class UsersController < ApplicationController
   #新規ユーザー登録用のメソッド
   def new
      @user = User.new
   end

   #フォームを受け取った後の処理
   def create
       @user = User.new(users_params) #後のプライベートメソッドで定義
       if @user.save
            flash[:notice] = "登録完了"
            redirect_to '/login'
       else
            flash[:notice] = "登録に失敗しました"
            render "new"
       end
    end

     private
      def users_params #フィルターをかけて受け取るパラメーターを制限
           params[:user].permit(:name, :password, :password_confirmation)
     end

end

/app/views/users/new.html.erbを作成

$vim app/views/users/new.html.erb

<h1>新規ユーザー登録</h1>
<pre> <%= flash[:notice] %>
<%= form_for @user do |f| %>
<%= f.label :ユーザー名 %>:<%= f.text_field :name %>
<%= f.label :パスワード %>:<%= f.password_field :password %>
<%= f.label :確認用パスワード	 %>:<%= f.password_field :password_confirmation %>
<%= f.submit %>
<% end %>

/config/routes.rb を編集
$vim /config/routes.rb
//以下を追加
resources :users, only: [:new, :create]

サーバー起動
$rails s

ここにアクセス
http://localhost:3000/users/new

##ログイン部分の実装 セッションを利用してログイン情報を保持する。

ログインコントローラーを作成
$rails g controller logins

ログインコントローラーの中身を実装

$vim app/controllers/logins_controller.rb

class LoginsController < ApplicationController
  def show
      render "new"
  end

  def create
    user = User.find_by_name params[:name]
    if user && user.authenticate(params[:pass])
      # セッションのキー:user_idへユーザーのIDを登録
      session[:user_id] = user.id
      redirect_to root_path
    else
      # flash変数にメッセージをセット
      flash.now.alert = "もう一度入力してください。"
      render "new"
    end
  end

  def destroy
    session[:user_id] = nil
    @current_user = nil
    redirect_to login_path
  end
end

//ログインビューの中身も実装

$vim app/views/logins/new.html.erb

<h1>ログイン画面</h1>

<!-- フラッシュ変数のメッセージを表示(ログインエラー時のみ) -->
<p><font color=red><%= flash[:alert] %></font></p>
<%= form_tag login_path do %>
<table id="login_form">
  <tr>
    <td><%= label_tag :name, 'ユーザー名' %></td>
    <td><%= text_field_tag :name, params[:name] %></td>
  </tr>

  <tr>
    <td><%= label_tag :pass, 'パスワード' %></td>
    <td><%= password_field_tag :pass, params[:pass] %></td>
  </tr>

  <tr>
    <td><%= submit_tag "ログイン" %></td>
  </tr>
</table>
<% end %>

ルーティングを行う

$vim config/routes.rb

以下を追加
resource :login

ビューからログインユーザーを参照できるようにする    $vim app/controller/application_controller.rb

以下のように変更

class ApplicationController < ActionController::Base
  protect_from_forgery

  def current_user
    if session[:user_id]
      # @current_userがnilかfalseならログインユーザーを代入
      @current_user ||= User.find(session[:user_id])
    end
  end

  helper_method :current_user
end

indexを編集
$vim /app/views/top/index.html.erb

以下を追加

<p><%= link_to "新規登録","/users/new" %></p>
<% if current_user == nil %>
  <%= link_to "ログイン", login_path %>
<% else %>
  <p><%= link_to "todo作成","login_todos"%></p>
  <%= link_to 'ログアウト', login_path, :confirm => 'ログアウトしますか?', :method => :delete %>
<% end %>

以下にアクセスすると新規登録、ログインのリンクがあるトップページが出現するはず
http://localhost:3000/

##todoリストの作成 SWAFS October#1 - Ruby on Railsでもやったようにtodo部分を作っていく。

todoの基本部分を作成

$rails g scaffold LoginTodos name:string todo:string done:boolean
rake db:migrate

app/views/login_todos/_form.html.erbを編集

$vim app/views/login_todos/_form.html.erb

以下をコメントアウトする
<%= f.label :name %>
<%= f.text_field :name %>

代わりに以下を追加
<%= f.label :name %>
<%= f.text_field :name, value:current_user.name, :readonly => true%>

app/views/login_todos/index.html.erbを編集

$vim app/views/login_todos/index.html.erb

<h1>Listing login_todos</h1>
あなたは<%= current_user.name %>です。


<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Todo</th>
      <th>Done</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @login_todos.each do |login_todo| %>
      <tr>
        <td><%= login_todo.name %></td>
        <td><%= login_todo.todo %></td>
        <td><%= login_todo.done %></td>
    
        <% if current_user.name == login_todo.name then %>
           <td><%= link_to 'Show', login_todo %></td>
           <td><%= link_to 'Edit', edit_login_todo_path(login_todo) %></td>
           <td><%= link_to 'Destroy', login_todo, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <% end %>

      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Login todo', new_login_todo_path %>

**これで一応完成

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment