ruby-on-railschargify

Redirect if an object is not found


I am using the chargify_api_ares gem to search for a Chargify Subscription.

@current_subscription = Chargify::Subscription.find_by_customer_reference(@dealer.id)
redirect_to(dealers_path) unless @current_subscription

However, if no subscription is found it never makes it to the next line where it redirects because find_by_customer_reference spits out a 404 if it doesn't find anything, but I'd like some way for it to return nil instead so I can make it to the next line where I redirect the user out of there.

Does anyone know how I can make fail softly or a better way I can redirect the user if no object is found? Thanks.


Solution

  • Presumably the method is raising an ActiveRecord::RecordNotFound exception, which you can catch and turn into a redirection:

    begin
      @current_subscription = Chargify::Subscription.find_by_customer_reference(@dealer.id)
    rescue ActiveRecord::RecordNotFound
      redirect_to dealers_path
    end