Reputation: 128
I need to check if a User exists.
This works:
User.exists?(id:123) => true
However the ID won't be always available, just the "name_parameterized" column. So, How to do something like this?:
User.exists?("name_parameterized='peter-parker' OR id=123")
Thanks.
Upvotes: 0
Views: 62
Reputation: 134
User.where(id: 123).or(User.where(name: 'peter-parker')).exists?
Update This works in rails 5. For older versions use
User.where('id=? OR name=?', 123, 'peter-parker').exists?
Upvotes: 1
Reputation: 211670
You can do this with two different queries, which is often faster due to indexing:
User.exists?(name_parameterized: 'peter-parker') or User.exists?(id: 123)
You could also collapse that into a single query, though that could be messier from a query optimizer perspective:
User.where(name_parameterized: 'peter-parker').or.where(id: 123).any?
Upvotes: 2