我设置我的控制器以允许过滤器中的例外URL中的特定标记。
对于本演示的所有意图和目的,令牌是字符'a'。
但现在,当我转到该操作的网址时,例如stage / 7 / compare和我没有登录,我可以看到....如何设置我,以便如果令牌参数不在URL中,它会将用户发送到登录,但如果允许他们在没有登录的情况下看到它(例如stages/7/compare?token=a
)?
这就是我的阶段控制器的样子:
class StagesController < ApplicationController
before_filter :check_token, :only => [:show]
before_filter :authenticate_user!, :except => [:compare]
filter_access_to :all
def show
@stage = Stage.find(params[:id])
render :layout => 'comparison'
title = @stage.name
#@upload = Upload.find(params[:id])
# respond_to do |format|
# format.html # show.html.erb
# format.xml { render :xml => @stage }
# end
end
def compare
@stage = Stage.find(params[:id])
title = @stage.name
end
private
def check_token
stage = Stage.find(params[:id])
redirect_to(params[:token] == "a" ? compare_stage_path(stage) : root_path)
end
end
EDIT1:
如果我更改了:check_token to :only [:compare]
这就是我的日志所做的事情:
Started GET "/stages/7/compare" for 127.0.0.1 at 2011-03-30 18:45:05 -0500
Processing by StagesController#compare as HTML
Parameters: {"id"=>"7"}
User Load (1.9ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
#<User id: 1, email: "test@abc.com", encrypted_password: "$2a$10$qUbNGm6lZ366jRiE0vK0gOpxbGXD5JmfqWmH1lfLlCEC...", password_salt: "$2a$10$qUbNGm6lZ366jRiE0vK0gO", reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 251, current_sign_in_at: "2011-03-30 23:28:18", last_sign_in_at: "2011-03-30 21:57:13", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", username: "test", f_name: "Test", l_name: "User", created_at: "2011-01-22 07:17:45", updated_at: "2011-03-30 23:28:18", invitation_token: nil, invitation_sent_at: nil, plan_id: 3, current_state: nil, confirmation_token: nil, confirmed_at: "2011-02-11 23:19:15", confirmation_sent_at: "2011-02-11 23:18:20">
Stage Load (0.3ms) SELECT "stages".* FROM "stages" WHERE ("stages"."id" = 7) LIMIT 1
Redirected to http://localhost:3000/
Completed 302 Found in 190ms
即。它重定向到我的root_path。
答案 0 :(得分:2)
您的问题询问了您的compare
操作,但您的before_filter
设置为仅对show
操作进行操作。
before_filter :check_token, :only => [:compare]
答案 1 :(得分:0)
此代码修复了此问题:
class StagesController < ApplicationController
before_filter :check_token_or_user, :only => :compare
before_filter :authenticate_user!, :only => :show
def show
@stage = Stage.find(params[:id])
render :layout => 'comparison'
end
def compare
@stage = Stage.find(params[:id])
end
private
def check_token_or_user
if !user_signed_in && params[:token].blank?
redirect_or_someting
elsif !user.signed_in && params[:token].present? && params[:token] == "a"
# do nothing, they can view the page
elsif user_signed_in?
# do nothing, they can view the page
end
end
end