Search code examples
sqlruby-on-rails

Check if record does NOT exist in Rails (from array of ids)?


I can do this to check if a record(s) exists (say id "1" exists, but "2" and "3" don't):

Model.exists?(:id => [1, 2, 3]) #=> true

How do I do the opposite, so:

Model.not_exists?(:id => [1, 2, 3]) #=> true

Solution

  • Edit: Please don't use this method. Even if it works it's not optimal since it loads all records instead of only testing their existence. This is a better way of doing it.


    If you only need search records through ID you can try this

    class Model
      def self.not_exists?(ids)
        self.find(ids)
        false
      rescue
        true
      end
    end
    

    If any of the IDs does not exist the find method will raise a ActiveRecord::RecordNotFound exception that we simply catch and return true.