0

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?

Abhi
  • 4,123
  • 6
  • 45
  • 77

1 Answers1

2

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
Community
  • 1
  • 1
AbM
  • 7,326
  • 2
  • 25
  • 28
  • `params[:id]` will always be a string. You'll need to cast it first. – j-dexx Oct 16 '15 at 15:37
  • 1
    @japed that is why @AbM suggested implementing an `is_integer?` method (see the linked SO question in answer) – Wizard of Ogz Oct 16 '15 at 15:39
  • [AbM](http://stackoverflow.com/users/2697183/abm) Thanks for replying. I have already tried this fix. But, I was searching for an one liner solution. – Abhi Oct 16 '15 at 15:47
  • Also, as mentioned in the comments of the [SO question](http://stackoverflow.com/a/1235891/2968762), `"01".to_i.to_s is not equal to "01"` – Abhi Oct 16 '15 at 15:54
  • Are you expecting an `id` to be passed as `"01"`? If so, try using the [regex solution](http://stackoverflow.com/a/18129961/2697183) – AbM Oct 16 '15 at 15:58
  • @AbM I'm expecting token may be starting with 0, which is rare but a possibility. Apart from this, is there a possible single line code? – Abhi Oct 16 '15 at 16:11
  • Then you're fine. If you implement `to_i.to_s` for checking `is_integer?`, then if the `params[:id]` starts with `"0"`, it will execute the `else` block, and only look for users based on the `token`. The one liner will still need to check `is_integer?` – AbM Oct 16 '15 at 16:16