user502052
user502052

Reputation: 15258

Trouble using a 'before_filter' method and rendering partials

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)

Are 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?

Upvotes: 1

Views: 1683

Answers (4)

Dmitry Maksimov
Dmitry Maksimov

Reputation: 2861

  1. Move authorize method to ApplicationController

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

Upvotes: 1

ALW
ALW

Reputation: 1017

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)

Upvotes: 0

megas
megas

Reputation: 21791

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

Upvotes: 0

Shiv
Shiv

Reputation: 8412

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.

Upvotes: 0

Related Questions