Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between session and params in Controller class

I am looking at a rails example for shopping carts and in the ApplicationController class I see code like this:

class ApplicationController < ActionController::Base
  protect_from_forgery

  private

    def current_cart 
      Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      cart = Cart.create
      session[:cart_id] = cart.id
      cart
    end
end

so it is using a Cart.find(session[:cart_id])

Then I go to carts_controller.rb and CartController class and I see code like this:

 def update
    @cart = Cart.find(params[:id])

    respond_to do |format|

so here it is using Cart.find(params[:id])

But I can't understand why we used session to pass params in the AppController but we used normal params in the CartController and could we use swithc use of them ? or is it how rails works and always session goes to AppController? Would be greta if someone can explain this in more details

like image 525
Bohn Avatar asked Dec 26 '22 11:12

Bohn


1 Answers

params live in the url or in the post body of a form, so it vanishes as soon as the query is made.

Session persists between multiple requests (the info are often stored in cookies but this depends on your configuration).

To be short:

  • params: one request only (creation of one object, access to one particular page)
  • session: info to be persisted (cart, logged user..)
like image 54
apneadiving Avatar answered Mar 01 '23 23:03

apneadiving