Processing ActiveRecord :: RecordNotFound in Ruby on Rails

In my editing action I have

@item = current_user.shop.items.find(params[:id]) 

Thus, the user can only edit items that belong to their store. If they try to edit an item that does not belong to their store, then they get an ActiveRecord :: RecordNotFound error.

What is the best way to handle this error in such situations? should i make an exception? should I redirect somewhere and install flash (if so, how do I do it), should I just leave it as it is? Any advice is appreciated.

thanks

+6
source share
3 answers

Add something like the following to the controller:

 rescue_from ActiveRecord::RecordNotFound do flash[:notice] = 'The object you tried to access does not exist' render :not_found # or eg redirect_to :action => :index end 
+20
source

+1 for @Koraktor solution. If you want to avoid ActiveRecord :: RecordNotFound, you can use the find_by method instead of find.

 @item = current_user.shop.items.find_by_id(params[:id]) if @item.nil? flash[:error] = "Item not found" else # Process the @item... end 
+20
source

In addition, you must set the http status when rendering the template:

 rescue_from ActiveRecord::RecordNotFound do render :not_found, :status => :not_found end 

The Rails guide (section 2.2.13.4) opens for a list of states.

As indicated elsewhere (for example here ), you should never redirect when sending 40x status, only 30x statuses should allow redirection. Thus, you may come across a strange page "You are being redirected" when trying to redirect with: not_found status.

+4
source

Source: https://habr.com/ru/post/893486/


All Articles