Rails Session value not set problem

I waisted my couple of hours to this problem and I don’t want you to do same.

Problem

# I set session in one controller but when I tried to render from another 
# controller I got nil

def bid_details
 alert_id = params[:id]
 alert = @user.alerts.find(alert_id)
 raise ActiveRecord::RecordNotFound if alert.inactive?
 session[:bid_details] = alert.bid_id
rescue ActiveRecord::RecordNotFound => e
 logger.error e.message
 render '/public/404.html', status: 404 and return false
end

Solution : What had happened is, previously there was no view template assigned to the controller, Rails resets the session when exception occurs. When I rendered something then only my app was able to set session from that controller’s action.

def bid_details
 alert_id = params[:id]
 alert = @user.alerts.find(alert_id)
 raise ActiveRecord::RecordNotFound if alert.inactive?
 session[:bid_details] = alert.bid_id
 # Rendering a view helped me get out of that pit
 render text: 'hello'
rescue ActiveRecord::RecordNotFound => e
 logger.error e.message
 render '/public/404.html', status: 404 and return false
end

sd

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s