What is Rails way to DRY up the controller pattern of verifying :id is for a valid object (else redirect to error page)

Posted by jpwynn on Stack Overflow See other posts from Stack Overflow or by jpwynn
Published on 2012-09-30T03:16:23Z Indexed on 2012/09/30 3:37 UTC
Read the original article Hit count: 130

Filed under:
|

One of my controllers has close to 100 methods (eg routes) and nearly every one starts out the same code to redirect to an error page if the id param is invalid, followed by a similar check if the user that id doesn't belong in the user's account:

def something
  @foo = Foo.find_by_guid(params[:id])
  unless @foo
    @msg ||= { :title => 'No such page!',
      :desc => "There is no such page!" }
    render :action => "error" and return
  end
  unless @foo.owner_id == current_user.id
   @msg ||= { :title => 'Really?',
      :desc => "There is no such page." }
    render :action => "error" and return
  end

What is the best way to DRY up that sort of page id and owner id validation, given the code is doing a render ... and return?

What I don't want to do at this point is offload it to a blackbox roles and permissions library like CanCan... my goal is simply to have the in-app code to handle this be as clean as possible.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about dry