2008年12月6日土曜日

ちょっとルーティングを考える。

えーっと、とりあえず、"hogehoge"は、SNSです。
つうか、SNSになる予定です。

SNSの条件としては、いっぱいあるんだろうけど、とりあえず、
  • 登録しなければログインできない
  • ログインしなければコンテンツにはアクセスできない
というものがあるかと。

なんで、それに合わせて、ルーティングを考えましょうか。
条件になるのは、

  • ログインしていない状態ならば、/signup(/users/new)と/login(/session/new)以外は、全て / へリダイレクト
  • / は、/login(/sessions/new)
  • /users/user_idは、ユーザ・プロファイルを表示
  • ログインしている場合の / へのアクセスは、/users/user_idへ
ってな感じ?

で、app/controllers/application.rbに、before_filter :login_requiredをつけて、う〜ん、どうしよう...
actionに対応して、exceptは出来るけど、controllerに対応させるのは、出来ないよな...

と思っていたら、良いのを見つけました:-)
skip_before_filterなんていうメソッドがあるじゃないですか:-)

んで、こんな感じ。
diffで。

app/controllers/application.rb

+  before_filter :login_required

app/controllers/users_controller.rb

+  skip_before_filter :login_required, :only => [new:, :create, :activate, :suspend, :unsuspend, :destoy, :purge] 
 
+  #render show.rhtml
+  def show
+    @user = User.find(params[:id])
+  end

   def new
-    @user = User.new
+    if logged_in?
+      redirect_to(:controller => "users", :action => "show", :id => current_user.id)
+    else
+      @user = User.new
+    end
   end

app/controllers/sessions_controller.rb

+  skip_before_filter :login_required

   # render new.rhtml
   def new
+    if logged_in?
+      redirect_to(:controller => "users", :action => "show", :id => current_user.id)
+    end
   end
こんな感じで、おk?
users_controllerのskip_before_filter : login_requiredは、restful_authenticationが作ったactionだけに対応させた。
んで、ユーザ・プロファイル用に、users_controller.rbに、showを作ったよ。
で、sessions_controller.rbのnewアクションで、logged_in?して、合ってたら、current_userのidで、usersのshowアクションへリダイレクトする。
あと、users_controller.rbのnewアクションも、同じ事をするように。

おk?
おkでしょ?:-)

0 件のコメント: