Search code examples
rubysinatradatamapper

Checking if a record exists in Sinatra/DataMapper


I currently generate a user's profile page using their serial ID, like so:

get '/users/:id' do
  @user = User.get(params[:id])
end

This works great, until a number is entered that doesn't exist in the database.

I'm aware I can change User.get to User.get! to return an ObjectNotFoundError error if the record isn't found, but I'm not sure how I can use this to my aid.

I used to use .exists? when using RoR.

Any suggestions?

Thanks in advance!

Edit: I'm going to leave the question unanswered, as I haven't actually found a solution to what I asked in the title; however, I did manage to solve my own problem by checking to see if the :id entered is higher than the amount of users that exist in the database, like so:

if params[:id].to_i > User.count
  "This user does not exist."
else
  @users_id = User.get(params[:id])
  erb(:'users/id')
end

Solution

  • You already have the correct code:

    @user = User.get(params[:id])
    

    If no user exists with the given id, then #get will return nil. Then you can just do a conditional:

    @user = User.get params[:id]
    if @user
      # user exists
    else
      # no user exists
    end
    

    This is a very common pattern in Ruby which takes advantage of the "truthiness" of anything other than false or nil. i.e. you can say if 0 or if [] and the condition will evaluate to true

    You can recreate a .exists? method:

    class User
      def self.exists?(id_or_conditions)
        if id_or_conditions.is_a? Integer
          !! User.get id_or_conditions
        else
          !! User.first id_or_conditions
        end
      end
    end
    

    #get is similar to #find in rails, except it doesn't raise an error if the record is not found. #first is similar to #find_by in rails.