Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Controller Instance Variable not shared

My 'new' action generates the cart object @cart out of a session. When I call the 'update' action via AJAX the @cart object doesn't exist. Why is it not shared across the controller?

cart_controller.rb

def new
  @cart = Cart.new(session[:cart])
end

def update
  logger.debug @cart.present? # false
end
like image 580
danieljacky Avatar asked Jun 04 '26 16:06

danieljacky


1 Answers

@cart is an instance variable and it is not persisted between requests. And session is accessible between requests.

Basically if you have set some data into session then you can use that data between requests. As it was mentioned you can setup a before_filter and preset @cart instance variable before executing the update action.

class MyController < ApplicationController
  before_action :instantiate_cart, only: [:update] #is the list of actions you want to affect with this `before_action` method
  ...
  private

  def instantiate_cart
    @cart = Cart.new(session[:cart])
  end
end
like image 108
teckden Avatar answered Jun 06 '26 05:06

teckden