I need to add an id element into a session array in my rails application. I have the id when I bring up this view, product.id, and i have my session, called session[:cart], waiting for input.

I want to push that id into the session when I click on the link below.

<%= link_to "Add to Cart", controller: "my_cart" %>

Is there more to this link I add? i have been looking all over the internet and have not come up with exactly what I'm looking for.

Please help

有帮助吗?

解决方案

You need to pass your product.id to some controller/action where that controller/action will add the product id to the session. It cant be done on the browser side as Sessions are server driven

<%= link_to "Add to Cart", add_product_to_cart_path(:product_id => product.id) %>

and method would be something like

def add_product_to_cart

session[:cart] << params[:product_id]

end

其他提示

what you can do is make a action in controller where you can put product.id in your session[:cart] and put the path of that action into link_to for example:-

<%= link_to "Add to Cart",your_action_path %>

and to see the path of your action you can run rake routes in terminal, just put that path in there and it should do it

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top