1

before_filter를 사용하여 로그인해야하는 작업을 수행하려고하는데, 그렇지 않기 때문에 잘못된 것이 틀림 없습니다.before_filter가 "시작"하지 않는 것 같습니다.

로그인/로그 아웃뿐만 아니라 사용자가 로그인되어 있는지 (signed_in?) 확인하기 위해 'session_helper.rb'라는 헬퍼 파일을 사용합니다. before_filer와 함께 사용하는 동안 동작이나 뷰에서 사용하면 정상적으로 작동하지만 작동하지 않습니다. 사용자를 로그 아웃하고 '/ projects/new'에 액세스하려고 시도하면 가능하지 않지만 그렇게 할 수는 있습니다.

내가 뭘 잘못하고 있니?

프로젝트 컨트롤러 :

class ProjectsController < ApplicationController 
    before_filter :signed_in?, :except => [:index] // <-- doesn't prevent e.g. the action "new" to be executed 

    def new 
    @project = Project.new 
    @users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id])) 
    end 

    def index 
    @projects = Project.all 

    if signed_in? // <-- works as it should 
     @users_projects = Project.where(:user_id => current_user.id) 
    end 
    end 

    ... other actions ... 

end 

sessions_helper.rb는

module SessionsHelper 

    def sign_in(user) 
    cookies.permanent[:remember_token] = user.remember_token 
    self.current_user = user 
    end 

    def signed_in? 
    !current_user.nil? 
    end 

    def current_user=(user) 
    @current_user = user 
    end 

    def current_user 
    @current_user ||= User.find_by_remember_token(cookies[:remember_token]) 
    end 

    def sign_out 
    self.current_user = nil 
    cookies.delete(:remember_token) 
    end 
end 
+0

인증 보석을 사용하고 있습니까? –

+0

인증 보석으로 간주되는 경우 bcrypt-ruby를 사용합니다 ... – dracula

답변

6

따라서 before_filter는 다소 오도 된 이름입니다. 필터가 아닙니다. 다른 액션을 걸러 내고 거짓 값을 반환하면 발생하지 않도록하고, 진실을 반환하면 허용합니다. 그것은 정말로 다른 것보다 먼저 메소드를 호출하는 방법입니다. '경로가 실행 한 작업을 호출하기 전에 다음 방법을 호출하십시오'라고 생각하십시오.

실제로 레일 4에서는 before_filter에서 before_action으로 이름이 바뀌므로 앞으로 혼란이 완화 될 것입니다.

서명 된 입금에서 T/F를 반환하는 중입니까? 그래서 당신은 그 수표의 결과에 기초하여 특별한 것을하도록 말하지 않았으므로 그것을 확인하고 계속 진행하고 있습니다.

그래서 signed_in을 호출하는 대신? 이 같은 것이 작동합니다.

before_filter :authorize, :except => [:index] 

def authorize 
    redirect_to login_url, alert: "Not authorized" if !signed_in? 
end 

홉이 도움이됩니다.

+0

나를 위해 이것을 해결해 주셔서 고마워요! – dracula

+0

옳다면 항상 대답을 수락 할 수 있습니다! –

1

난 항상 before_filter는 예외를 발생 않거나 현재 로그인이없는 경우 다른 페이지로 리디렉션 보았다. false를 반환하면 페이지가 렌더링되지 않습니다.

+0

감사합니다. 작동시키기 위해 리다이렉션을 사용해야했습니다. :) – dracula