Home > Mobile >  How to optimize to 1 query?
How to optimize to 1 query?

Time:11-14

It seems to me that this code can be simplified to one query, but I cannot understand how Is it possible to do it somehow?

users_ids = ::User.find_by(id: id)&.something.presence || ::User.all.pluck(:id)

I tried to make it with SQL, but it didn't work

CodePudding user response:

Are you trying something like this OR

Book.where(category: "Programming").or(Book.where(category: "Ruby"))

https://guides.rubyonrails.org/active_record_querying.html#or-conditions

CodePudding user response:

You could first check if there's a user in the database with that id and with something other than NULL, if not then you use an OR operator and bring them all;

User.where('(id = ? AND something IS NOT NULL) OR TRUE', id)
  • Related