开发者

How to access the flash and redirect_to from a filter class

I'm trying to use a class as a before filter for multiple controllers. Because the filter must do slightly different things based on which controller is calling it, it seems like I need to use a class as a filter in order to get the controller passed in to filter.

So far, I have something like

class ShowFilter
def self.filter(controller)
  c_name = controller.controller_name
  object_id = controller.params[:id]
  case c_name
    when "articles"
      article = Article.find(object_id)
      unless curr_user.can_see?(article)
        cont开发者_运维百科roller.redirect_to(:controller => "articles", :action => "index")
      end
    when "images"
      image = Image.find(object_id)
      unless curr_user.can_see?(image)
        controller.redirect_to(:controller => "images", :action => "index")
      end
  end
end

This class would be called as a :before_filter on the show action in the articles and images controllers.

My problem is that I get an error saying that 'redirect_to' is a protected method of whatever controller gets passed into the filter.

If I call

redirect_to(:controller => "images", :action => "index")

instead of

controller.redirect_to(:controller => "images", :action => "index")

I get an "undefined method 'redirect_to' for ShowFilter:Class" error.

If I define my class as

class ShowFilter < ApplicationController

I still get an undefined method error. I am having the exact same issues accessing the flash as well.

Is there a way to redirect inside of a filter class? Should I be using a different method to filter in order to be able to redirect and access the flash?


You could use controller.send(:redirect_to, "your url") to bypass the protected level of the method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜