带重定向的应用程序控制器级别验证

时间:2014-10-28 03:33:07

标签: ruby-on-rails ruby-on-rails-3 validation

我不确定确保每个用户都拥有某些必要属性的最佳方法是什么,如果他们不希望将其重定向到“新”用户,那么最好的方法是什么?页面例如。

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

以上示例存在缺陷,因为它会创建重定向循环。我可以定义一些关于创建这种验证的建议。谢谢

1 个答案:

答案 0 :(得分: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返回true / false布尔值,我建议将方法重命名为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