Michael Giovanni Pumo Michael Giovanni Pumo - 2 years ago 100
Ruby Question

Rails - obfuscate_id errors on find() in ApplicationController

I am using the obfuscate_id gem ( https://github.com/namick/obfuscate_id ).

We obfuscate ID's by inserting one line into the top of each model:


It works great and as expected. My ID's are obfuscated.

However, as part of some logic in my
, I have some logic to check the current user and each controller has access to these methods as helpers:

def current_user

@current_user ||= User.find(session[:user_id]) if session[:user_id]


However, I get an error:

Couldn't find User with id=5164061535

It doesn't seem to be able to convert the obfuscated ID back to its normal form for a find().

How can I get the controllers to recognise this obfuscation that's made in each model.

My user model is like so:

class User < ActiveRecord::Base

# This part obfuscates the user ID

has_one :profile, dependent: :destroy
has_many :pins
has_many :replies, through: :pins


Any ideas how I can get the
to recognise this? Doing find() in each controller itself is fine, but as
doesn't have its own model, it doesn't seem to know of it.


Answer Source

Weirdly enough, I ended up trying this:

@current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]

And it worked! But, why?

User.find() in itself was not working with this gem. So, although it's now working, it concerns me a little as to why exactly.

If anyone could add anything here that'd be great.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download