わたろぐ

仕事、読書、ガジェット、グルメ、写真、旅行など雑多な備忘

Ruby on Rails を触ってみる ⑥トップページの設定

今のところトップページは、ログインしていてもしてなくてもツイート一覧のページが表示される。せっかくユーザー認証機能を実装したので、ログインしていない→トップページ、ログインしている→ツイート一覧という感じにしたいとおもう。

rails generate でhome/indexを作成する。

$ rails g controller home index

作成されたViewファイル、home/index.html.erbを編集する。

<h1>Twiceへようこそ</h1>
<p>ログインして利用を開始しましょう</p>
<%= link_to (user_omniauth_authorize_path :twitter), class: "btn btn-large btn-primary" do %>
   Twitterでログイン
<% end %>

実行してみる。

ボタンの文字が黒い。Chromeの要素を検証で見てみると、scaffold.cssのa要素が効いてるみたい。調べてみると、bootstrapのリンクとかボタンの要素の文字の色が、scaffold.cssによって効かなくなることがあるみたい。

scaffold.css.scssのa要素のところをひと通りコメントアウトしておく。

/*
a {
  color: #000;
  &:visited {
    color: #666;
  }
  &:hover {
    color: #fff;
    background-color: #000;
  }
}
*/

ちゃんと表示されるようになった。

route.rbを編集して、この画面をrootに指定する。

$ git diff config/routes.rb 
-  root :to => 'tweets#index'
+  root :to => 'home#index'

これでlocalhost:3000/はhome/indexが表示されるようになる。

ログイン後はツイート一覧を表示したいのでcontroller/home_controllers.rbを編集する。

class HomeController < ApplicationController
  def index
    if user_signed_in?
      redirect_to tweets_path
    end
  end
end

これでログインするとrootはtweetに飛ばされる。

逆にログインしていないとhome/indexに飛ばされるようにしたい。 tweet_controller.rbも編集する。 privateのcheck_userメソッドを作成し、before_actionで実行する。

$ git diff app/controllers/tweets_controller.rb 
diff --git a/app/controllers/tweets_controller.rb b/app/controllers/tweets_controller.rb
index 0a17779..9a6ce3f 100644
--- a/app/controllers/tweets_controller.rb
+++ b/app/controllers/tweets_controller.rb
@@ -2,6 +2,7 @@
 
 class TweetsController < ApplicationController
   before_action :set_tweet, only: [:show, :edit, :update, :destroy]
+  before_action :check_user
 
   # GET /tweets
   # GET /tweets.json
@@ -90,4 +91,12 @@ class TweetsController < ApplicationController
     def tweet_params
       params.require(:tweet).permit(:tweet_id, :in_reply_to_status_id, :in_reply_to_user_id, :timestamp, :source, :tex
     end
+    
+    # ユーザがログインしていなければ、ホームにリダイレクト
+    def check_user
+      unless user_signed_in?
+        redirect_to :root
+      end
+    end
+    
 end

これでログインしていないユーザは強制的にホーム画面にリダイレクトされる。 いい感じ。 set home page and redirection twata701/twice GitHub

参考: bootstrap-rails で css がうまく適用されない場合の件