Hello, there is before_action:

before_action :set_film_session, only: [:show, :edit, :update, :destroy] 

His code

 def set_film_session @film_session = FilmSession.find(params[:id]) end 

The problem is that if you write for example in the address bar - / film_sessions / 0, then the error Couldn't find FilmSession with 'id' = 0 appears. Everything that I am writing inside the show or in set_film_session (after the assignment line) does not work because of this I can’t make a check.

    2 answers 2

    The find() method always throws an exception; if the object you are looking for is not found, you can intercept it, but this is not the best practice. If you want to check the existence of a session, it is better to avoid generating an exception by using the where() method and then calling first() , for example

     def set_film_session @film_session = FilmSession.where(id: params[:id]).limit(1).first #if @film_session.present? #if @film_session.blank? end 

    After completing the query, you can check the contents of the @film_session variable.

    • first will make LIMIT 1 . And plowing ActiveSupport'ovye present? and blank? for the sake of checking for nil this is a bit overkill :) Is there nil? which is needed only to distinguish between false and nil , when false impossible here, that is, if @film_session generally sufficient. - D-side

    Couldn't find FilmSession with 'id' = 0

    This is an ActiveRecord::RecordNotFound . Know what Rails does in production with it?

    Gives the standard 404.

    Given the fact that your site is not expected to link to non-existent records (right?), It is quite a tolerable option to just leave everything as is . If the user himself wrote the link, he is quite ready to contemplate 404 due to an error in the URL.

    If you have the primary key of this table id , then exceptions can be avoided by finder field, which in case of absence returns nil :

     @film_session = FilmSession.find_by_id(params[:id]) 

    This is one of the moments where Rails is not completely consistent : it would be possible to assume that find will return nil , and find! explode with the exception ...
    But no, the find! method find! does not exist.

    • Thank you, informative) - Maxim Cherevatov