button_to (passing paramters again)

I am pretty close to figuring this out…

I’ve got this in my product show page…I’m trying to pass user_id & product_id to my products controller, add_to_cart method…

<%= button_to 'Add to Cart', {:controller => "products", :action => "add_to_cart", :user_id=> session[:user_id], :product_id => @id } , :method=>:post %>


on the controller...

def add_to_cart(user_id, product_id)

@cart = Cart.new(user_id, product_id )

I've got this in my product show page....I'm trying to pass user_id & product_id to my products controller, add_to_cart method...

Accepting user_id as an untrusted input from the client is a Very Bad Idea. If it's a value saved in session you can and should fetch it in your controller.

<%= button_to 'Add to Cart', {:controller => "products", :action => "add_to_cart", :user_id=> session[:user_id], :product_id => @id } , :method=>:post %>

on the controller...

def add_to_cart(user_id, product_id)     @cart = Cart.new(user_id, product_id ) end

"wrong number of arguments (given 0, expected 2)"

So where are you setting user_id and product_id from the params? I assume you've looked at the log and confirmed the params hash contains what you expect?

Controller action methods do not take parameters. You get the parameters from the params hash. Also, as was mentioned, do not send user_id as a param. It is a security error, and you don’t need to because you can access the session in the controller:

def add_to_cart

product_id = params[“product_id”]

user_id = session[“user_id”] @cart = Cart.new(user_id, product_id)

end

ok, still confused…

I’ve defined my parms like this…

def cart_params
  # params.fetch(:cart, {})
  params.require(:cart).permit(:user_id, :product_id )

end


Have this in my controller.

def add_to_cart

product_id = params[‘id’] user_id = session[‘user_id’] @cart = Cart.new(user_id, product_id)

end

Not sure what to put in the show page, to pass these values to the controller.

I’ve got a few rails books, and not one of them cover this.

ok, still confused....
I've defined my parms like this...

def cart_params   # params.fetch(:cart, {})   params.require(:cart).permit(:user_id, :product_id )

end    Have this in my controller.

def add_to_cart

  product_id = params['id']   user_id = session['user_id']   @cart = Cart.new(user_id, product_id)

end

Try this:

product_id = cart_params[:product_id] user_id = session['user_id'] @cart = Cart.new(user_id, product_id)

Not clear what params[:id] would be set to in your example, but you went out of your way to whitelist cart[product_id], so that's what I think you should use.

Walter

I finally got it working. I went to a local ruby on rails meetup and got some help on the issue.

I needed to use current_user.id and params[:product_id] for my parameters in my function.

Thanks,

Joe