toshieeeee
7/14/2017 - 10:12 AM

often use processing on rails

often use processing on rails

▼each


<% @users.each do |user| %>

<% end  %>

▼ form


<%= form_tag("/login") do %>

  <p>メールアドレス</p>
  <input name="email" value="<%= @email %>”> 
  <p>パスワード</p> 
  <input type="password" name="password" value="<%= @password %>”> 

  <input type="submit" value="ログイン">

<% end %>

▼ エラー出力 - each


    <% @user.errors.full_messages.each do |message| %>

        <div class="form-error">
                <%= message %>
        </div>

    <% end %>

▼ エラー出力 - Val


    <% if @error_message %>

        <div class="form-error">
            <%= @error_message %>
        </div>

    <% end %>

▼ セッション情報出力


    <% if session[:user_id] %>

        <li>ログインユーザー: <%= session[:user_id] %></li>

    <% end %>

▼ ログインユーザー管理 - Application Controller


    # メソッド実行
      
    before_action :set_current_user

    #「すべてのコントローラー」で共通する処理を定義

    def set_current_user 

    @current_user = User.find_by(id: session[:user_id])
    # Userインスタンスの取得

    end

▼ ログインユーザー認証 - Application Controller


    # 実行 - onlyを用いて、適用したいアクションを指定することができる。
    
    before_action :authenticate_user,{only: [:index,:show,:edit,:update]}

    #「すべてのコントローラー」で共通する処理を定義

    def authenticate_user

    if @current_user == nil
    
      flash[:notice] = "ログインが必要です"
      redirect_to('/login')
      
    end

▼ ログインユーザのアクセスを制限 - Application Controller


    def forbid_login_user 

        if @current_user
        flash[:notice] = “すでにログインしています”
        redirect_to(“/posts/index”)
        end

    end
    
    # それぞれのコントローラーで、制御したいアクションを定義
    
    before_action :forbid_login_user,{only: [:top]}

    before_action :forbid_login_user,{only: [:new,:create,:login_form,:login]}