Michael Giovanni Pumo Michael Giovanni Pumo - 5 months ago 26
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:

obfuscate_id


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

However, as part of some logic in my
ApplicationController
, 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]

end


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
obfuscate_id

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

end


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

Thanks,
Michael.

Answer

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.

Thanks!

Comments