Reputation: 1615
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
Reputation: 670
You can do this as well, if you want a one liner:
(session[:cart] ||= []) << `some data`
Upvotes: 2
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
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