Reputation: 4261
I have the following active record query:
User.where(["id = ? OR token = ?", params[:id], params[:id]]).first
Here, params[:id] = 9MrEflgr
PROBLEM
As per logic, params[:id]
can be numeric id or alphanumeric token.
I want to get something like User.find_by_id_or_token(params[:id])
in where clause.
Here, since the params[:id]
starts with '9', so active record gives me user with id 9 instead of checking for token field. How to avoid this?
Upvotes: 0
Views: 58
Reputation: 7779
As the comment mentioned, you need to check if the params is an integer. This SO question has good suggestions on how to do that (where you can implement is_integer?
below).
if params[:id].is_integer?
User.where(["id = ? OR token = ?", params[:id], params[:id]]).first
else
User.where(["token = ?", params[:id]]).first
end
Upvotes: 2