Rails on Heroku: nil session variables

I did a lot of research and did not find similar questions / answers, so I appreciate the help.

My application works fine in place, but when I click on Heroku, it pinches my session variables . In particular, it throws a NoMethodError for nil: NilClass when I try to access the attributes of the object contained in the session. I narrowed it down to a session after switching to options and success. However, I would prefer to use a session as my code is a bit cleaner.

I poked, and it seems to be happening with every session object. The quick context is that I create a new charge, then a new organization, and then connect the board with the organization.

The https protocol (this is the verification page), and these calls occur asynchronously via jQuery, although I'm not sure if this is important. Rails 3.2. Cedar / Postgres on Heroku. Sqlite3 / thin locally.

What happens to a Heroku session?

production.rb

config.session_store :cookie_store, :key => '_my_app_session', :domain => :all

application_controller.rb

...

helper_method :current_charge
def current_charge
  @_current_charge ||= session[:current_charge_id] &&
  Charge.find_by_id(session[:current_charge_id])
end

...

charges_controller.rb

def create
  @charge = Charge.new(params[:charge])
  if @charge.save
    session[:current_charge_id] = @charge.id
  ...
end

organizations_controller.rb

def create
  @organization = Organization.new(params[:organization])
  if @organization.save
    @charge = current_charge
    @charge.organization_id = @organization.id
    @charge.save!
  ...
end

Cedar log (thrown at organization_controller.rb)

NoMethodError (undefined method `organization_id=' for nil:NilClass):
+3
source share
1 answer

When you create an instance of a record with new, the record is not stored in the database until it is saved, and no identification is assigned to the record until it is saved.

In your code:

def create
  @charge = Charge.new(params[:charge])
  session[:current_charge_id] = @charge.id
  ...
end

@charge.id , id. create charge_controller.rb, id:

def create
  @charge = Charge.create(params[:charge])
  session[:current_charge_id] = @charge.id
  ...
end

:

def create
  @charge = Charge.new(params[:charge])

  @charge.save

  session[:current_charge_id] = @charge.id
  ...
end
+1

All Articles