2014-10-28 59 views
0

我不确定确保每个用户都具有某些必要属性的最佳方法,并且如果他们不是我想将其重定向到“新”页面,例如带重定向的应用程序控制器级别验证

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    before_filter :authenticate_user!, :valid_location 

    def valid_location 
    if (current_user.location.nil? || current_user.location.city.nil?) 
     redirect_to new_user_locations_path(current_user.id) 
    else 
     true 
    end 
end 

上面的例子有缺陷,因为它创建了一个重定向循环。我可以明确地使用一些关于创建这种验证的建议。谢谢

+0

,只需添加'skip_before_filter:valid_location ,只有::new来修复重定向循环。还有,你不需要返回true,所以只需删除其他部分。 – jvnill 2014-10-28 03:43:09

回答

1

创建重定向循环的原因是因为valid_location方法也在负责new_user_locations_path的控制器上调用。为了防止这种情况,您需要确保控制器不会使用skip_before_filter(在Rails 4中为skip_before_action)运行该过滤器。类似的问题是answered here

class LocationsController < ApplicationController 
    skip_before_filter :valid_location, only: [:new, :create] 
    #... 
end 

因为valid_location返回真/假布尔,我建议重命名方法valid_location?invalid_location?和重构逻辑一点:

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    before_filter :authenticate_user!, :redirect_invalid_locations 

    private 
    def redirect_invalid_locations 
    redirect_to(new_user_locations_path(current_user)) if invalid_location? 
    end 

    def invalid_location? 
    current_user.try(:location).try(:city).nil? 
    end 
end 


class LocationsController < ApplicationController 
    skip_before_filter :redirect_invalid_locations, only: [:new, :create] 
end  
在位置控制器
+0

非常感谢。我只能改变一件小事。添加:创建到:skip_before_filter:redirect_invalid_locations,只:[:new,:create]否则我得到:过滤器链暂停为:redirect_invalid_locations呈现或重定向 – Richardlonesteen 2014-10-28 04:28:13