Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 319
Lance Avatar asked Dec 01 '10 16:12

Lance


2 Answers

just add a ! operator

!Model.exists?(:id => [1, 2, 3]) #=> true 
like image 193
GSto Avatar answered Oct 15 '22 16:10

GSto


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.

Excuse my English :)

like image 22
afgomez Avatar answered Oct 15 '22 17:10

afgomez