Paul Byrne
Paul Byrne

Reputation: 1615

Adding an array to the session array in Rails

I am using a session based cart for a rails application where I am not allowed to use a database.

I have written this helper to create a the cart if it does not exist in my line_items controller.

def ensure_cart_exists
  session.push(Array(:cart)) unless session.include?(:cart)
end

But I get this error

undefined method `push' for #<ActionDispatch::Request::Session ...

The line of code works in the IRB when I try it on an array. Is there something I don't understand about the session array that prevents me from using it here?

Upvotes: 0

Views: 4468

Answers (3)

Takehiro Mouri
Takehiro Mouri

Reputation: 670

You can do this as well, if you want a one liner:

(session[:cart] ||= []) << `some data`

Upvotes: 2

ReggieB
ReggieB

Reputation: 8257

A stylistic addition, but methods called things like ensure_something_exists are a bit of a red flag to me.

Rather than doing this:

ensure_cart_exists
session[:cart] << 'some data'

You should set up a method that will exposes the underlying item if it exists or creates the object if not. Then use that method for everything. So:

def cart
  session[:cart] ||= []
end

cart << 'some data'

Upvotes: 3

spickermann
spickermann

Reputation: 107142

The session is a hash like object, it does not act like an array. Do this instead:

def ensure_cart_exists
  session[:cart] ||= []
end

Upvotes: 4

Related Questions