开发者

Trouble using a 'before_filter' method and rendering partials

开发者 https://www.devze.com 2023-02-18 07:32 出处:网络
I am using Ruby on Rails 3 and I am trying to understand the behavior of the before_filter method in a controller.

I am using Ruby on Rails 3 and I am trying to understand the behavior of the before_filter method in a controller.

In my controller I have

class UsersController < ApplicationController
  before_filter :authorize

  def show
    ...
  end
end

If I browse, for example, the page http://<my_web_site>/user/1 (that loads the users/show.html.erb view file populated of data from the User with ID 1) the before_filter works as well. That is, the authorize method does what it must do.

If I render the users/show.html.erb view file as a template for another controller (example: the PostsController) this way

# This code is in the `post/show.html.erb` file
<%= render :template => "/users/show", :locals => { :user => @user } %>

the before_filter doesn't work. That is, the authorize method seams do not run.

Why?! There is a reason for that behavior or I am wrong somewhere?


UPDATE (after the @brad comment)

A开发者_运维技巧re you rendering that view as a partial template from within the users controller? If not the before_filter won't apply

If it is as @brad say in his comment, how can I make the before_filter to work rendering that view for another controller than UsersController?


  1. Move authorize method to ApplicationController

  2. Add before_filter to each controller where you want to check user authorization.


When you render a template or a view file/partial, it is not really treated as a request on your controller, hence the filters dont apply.


Firstly you should understand the routing in the Rails. When you type in the browser http://<my_web_site>/user/1 then it goes to route file, after this to proper controller's action, after that controller initiate the render view. And controller has these callbacks, when some action is initiated then these callbacks should act before or after controller's action. So in your case you're calling partial template without any controller's involving


before_filter applies to controller actions, not rendering actions.

One solution, then, is to abstract your authorization logic out into a helper that can be used when you're rendering your partial:

if authorized?
  render :partial => 'users/show'
end

Another solution is to implement authorization at the model level, using something like the declarative_authorization gem (https://github.com/stffn/declarative_authorization)

0

精彩评论

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