Victor
Victor

Reputation: 13388

Trigger ActiveRecord::RecordNotFound instead of returning nil

Using Rails 3.2. I am implementing vanity url for user URL:

# routes.rb
resources :users
match 'u/:login' => 'users#show', :as => :main_user

# users_controller.rb
class UsersController < ApplicationController
  def show
    @user = User.where(:login => params[:login]).first
  end
end

Usually if we use @user = User.find(params[:id]), it would return ActiveRecord::RecordNotFound, which then redirects to 500 or 404 (not sure which one would be redirected to, but that's not important).

But in the case above, it would just return @user = nil and continue rendering show action. How can I code it in a way it works the same like searching for id?

Upvotes: 0

Views: 292

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

You can use .first! (Docs) to raise an ActiveRecord::RecordNotFound error in case no record could be found.

@user = User.where(:login => params[:login]).first!

Upvotes: 3

Related Questions