Passing controller method attributes in before_filter methods in Rails 3

666 views Asked by At

I'm trying to only allow access to galleries by users who have permission to view them. Galleries have many shared_users through permissions, and vice versa. Galleries also have only one owner. Owners and shared users are both of the User class. This all works fine. The issue that I'm having, however, is with my access filters.

I'm using the following code to see if a user is allowed to see the gallery they are trying to access:

def authenticate_viewers!
  if user_signed_in? && current_user.can_view?(@gallery)
    return true
  end
  redirect_to root_url,
    :notice => "You must have permission to view this gallery."
  return false    
end

As you can see, can_view? requires the @gallery that I'm setting up in the show method, but a before_filter won't let you access the attributes set up in the method, since it resolves before the method executes. Using an after_filter works, as long as an unauthorized user doesn't try to view the gallery. If it does, I get a DoubleRender error, since after_filter allows the page to render, then tries to redirect.

I just thought that I could perhaps use params[:id] instead of @gallery, though I haven't tried it yet, and ultimately this may be more efficient (passing an integer instead of an object). In any case, is there a way to make my current code work? or is it in my best interest to switch to using the params (if that's even going to work)?

1

There are 1 answers

0
Josh Kovach On BEST ANSWER

Wow, okay. It's really helpful just to start writing questions here on SO, because as I do, I typically get a brainstorm of how to solve the problem. Instead of using the @gallery object, I just use a Gallery.find(params[:id]) and everything works like a charm. Thank God I don't have to rewrite all my code.