0

I am working on a Ruby on Rails app which which has the following path to view a user's page

/pics/user/:id

:id being the generated id attribute. My question is that is the proper way for the the app to deal with a number that is not a user id in the place of :id.

The methods I was considering are; creating an Error page and redirect to it or redirecting to another page (in this case a page with the list of all the users) and generating an error message. Are either of these ideas correct, or should I do something else entirely? My goal is to adhere to proper ruby on rails and web conventions as closely as possible.

Thanks!

Btuman
  • 881
  • 2
  • 9
  • 37

3 Answers3

2

Usually you will be doing Model.find(params[:id]) and that will raise ActiveRecord::RecordNotFound that is to make the web server send a 404 Not Found response.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
clyfe
  • 23,695
  • 8
  • 85
  • 109
  • Just to be sure I understand, do you mean I alert the server informing it of the kind of error it is (404 in this case), and then have the server handle it? – Btuman Jan 04 '12 at 22:52
1

The only thing I think you should really do is set the status of your response to 404 (pass :status => 404 to render.

Whether your 404 page is just a dumb 'sorry nothing found' page or something more helpful (e.g. with suggestions of what the user might have wanted) is up to you

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
0

I use the following method, although I think some RoR purists would argue that this isn't the proper way to do it... but it does work, very nicely. I much prefer this method over a useless 404 page:

users_controller.rb

  before_filter :get_user, :only => [:show, :edit, :create, :update]

  # ... all your methods ...

  private
    def get_user
      @user = User.find(params[:id])
      rescue ActiveRecord::RecordNotFound
        redirect_to users_path, :alert => "User not found" and return false
    end
bricker
  • 8,911
  • 2
  • 44
  • 54
  • What about this method would upset ROR purists? – Btuman Jan 05 '12 at 01:00
  • The issue with redirecting to an index page on errors is that you do not get to set a proper status code. If you eventually want to use your controllers as a webservice, it is better to have them act in a RESTful way, which includes using error status codes on errors and not redirecting. See this answer for a railsy way to do it by using the bang methods which will raise RecordNotFound exceptions https://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails – Jorn van de Beek Oct 15 '15 at 10:32