ActiveRecord::RecordNotFound not raising with non-id in Rails 3
In this scenario I look for the username by getting it through the url as 开发者_Go百科site.com/john
Probably because of the type of query, when the URL has a non-existent username Rails is not retuning a RecordNotFound exception and so no appropriate 404 page is rendered. The current fix I did is like this code, but I would like to get the exception from Rails and not like this that looks very smelly.
def show
@user = User.first(:conditions => ["lower(username) = ?", params[:username].downcase])
if @user
...
else
redirect_to '/404.html'
end
end
Thank you
You're right that it's the type of query: .first
and other associated shortcuts return nil
instead of raising the RecordNotFound
exception. If you change the code around a bit and call User.find_by_username! params[:username].downcase
, it will revert to raising the exception on zero records.
See Raising an ActiveRecord error on RecordNotFound
精彩评论