Jngai1297
Jngai1297

Reputation: 2495

Having Trouble Using Session in Rails undefined local variable or method

I have a devise registration controller here

class Students::RegistrationsController < Devise::RegistrationsController

  def after_sign_up_path_for(resource)
    '/events/new'
  end 

  def after_inactive_sign_up_path(resource)
    '/events/new'
  end 

  def brand
    brand ||= Brand.find(params[:brand]) 
    session[:brand] = Brand.find(params[:brand]) #not working 
  end 
  helper_method :brand 
end

after somebody sign up it will send them to events/new page

Before someone goes to the sign up page, they will have to go through a brands page

=link_to t('slide2.apply_here'), new_student_registration_path(:brand => brand.id),class: "button-component", style: "font-size: 14px; padding: 10px 50px;"

please note that the brand id is getting passed through the link_to as a params to the registration controller. I have the brand method to capture the brand id, find the brand and use it on the view in the sign up page.

I want to do the same thing for events/new hence storing the Brand in the session.

I keep on getting undefined local variable or method brand.

I have this in events new view

%h3=brand.name

I know session should be short, it should just be

session[:brand] = params[:brand]

but then I am getting my signup page undefined now, its messing up my helper method.

updated

I just dropped this in my events new view

.row
  .span4
    .accordion#picture_accordion.left
    =image_tag brand.image_url
    %h3=brand.name

Upvotes: 0

Views: 1418

Answers (1)

Max Williams
Max Williams

Reputation: 32933

When you say

brand ||= Brand.find(params[:brand]) 

this is like saying

brand = brand || Brand.find(params[:brand]) 

If brand hasn't been defined at this point you will get an "undefined local variable or method" error.

If you change it to an instance variable, @brand, it should work, since undefined instance variables evaluate to nil.

EDIT - this is my 'current_user' method, which sounds comparable.

def current_user
  @current_user ||= (session[:user_id] && User.find_by_id(session[:user_id]))
end

what's happening here is that the first time current_user is called, it loads the current user using session[:user_id] and saves it in an instance variable called @current_user. The next time current_user is called, in the same action, it will just use the object it has saved into the instance variable, and not load it out of the database again.

Note that in this system the controller and view code which wants to know who the current user is should always call current_user, not @current_user. @current_user is just used by the current_user method to save the value for the duration of the page render.

Upvotes: 1

Related Questions