2012-04-04 58 views
1

學習軌道開發,通常更喜歡搜索出一個答案,而不是浪費人們的時間,但這一直在我的頭上整夜。用戶導向軌道3中的高級限制

基本上我想要呈現與用戶相關的意見ALA的github等

我試圖按照奠定了這裏的說明: http://collectiveidea.com/blog/archives/2011/05/31/user-centric-routing-in-rails-3/

我此刻的認證是從railscast 「從零開始身份驗證 - 修訂」,它採用的會話,我sessions_crontroller.rb:

class SessionsController < ApplicationController 
    def new 
    end 

    def create 
     user = User.find_by_email(params[:email]) 
     if user && user.authenticate(params[:password]) 
     session[:user_id] = user.id 
     redirect_to root_url, notice: "Logged in!" 
     else 
     flash.now.alert = "Email or password is invalid" 
     render "new" 
     end 
    end 

    def destroy 
     session[:user_id] = nil 
     redirect_to root_url, notice: "Logged out!" 
    end 
end 

而且我的routes.rb:

C::Application.routes.draw do 

root :to => "static_pages#home", :constraints => LoggedInConstraint.new(false) 
root :to => "users#show", :constraints => LoggedInConstraint.new(true) 

resources :users 
resources :sessions 

按照我的理解,因爲我沒有使用cookies,所以在那篇博文中最後的評論建議使用request.session [:your_key]代替request.cookies.key?(「user_token」),在我仍然被帶到static_pages#home?如果有人能夠對這個話題發表一些看法,我將非常感謝。

我也道歉任何格式錯誤等,這是我的第一個問題在stackoverflow。

再次感謝!

回答

1

不知道與自己的問題,但我只是做了一種類似於此,所以也許我的代碼將幫助您:

我的路線:

# Except from config/routes.rb 
require File.expand_path("../../lib/role_constraint", __FILE__) 

MyApp::Application.routes.draw do 
    mount Resque::Server, :at => "/resque", :constraints => RoleConstraint.new('admin') 
    ... 
    ... 
    ... 

我的約束:

# lib/role_constraints.rb 
class RoleConstraint < Struct.new(:value) 
    def matches?(request) 
    request.session[:role] == value 
    end 
end 

我的會話控制器:

# app/controllers/sessions_controller.rb 
class SessionsController < ApplicationController 
    before_filter :require_user, :only => :destroy 
    def new 
    end 

    def create 
    user = User.find_by_username(params[:username]) 
    if user && user.authenticate(params[:password]) 
     session[:user_id] = user.id 

     # Just for /resque 
     # Not secure - if you change a user's role, it will not be updated here 
     # until they log out and log in again. 
     session[:role] = user.role 

     if user.email.nil? 
     redirect_to user, :notice => "Please add your email address to your account" 
     else 
     redirect_to root_url, :notice => "Logged in!" 
     end 
    else 
     flash.now.alert = "Invalid email or password" 
     render "new" 
    end 
    end 

    def destroy 
    session[:user_id] = nil 
    session[:current_project_id] = nil 
    redirect_to root_url, :notice => "Logged out!" 
    end 
end