pass parameter by link_to ruby on rails

Ruby on-RailsParameters

Ruby on-Rails Problem Overview


I have this line of code:

<%= link_to "Add to cart", :controller => "car", :action => "add_to_cart", :car => car %>

when im in the add_to_cart method...how can i call the :car please?

@car = Car.new(params[:car])

That doesn't work because it says that I'm trying to stringify it.

I don't understand what's wrong; because I used this to create new users and it worked fine.

By the way, car is my car object.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Solution 2 - Ruby on-Rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

Solution 3 - Ruby on-Rails

Maybe try this:

<%= link_to "Add to cart", 
            :controller => "car", 
            :action => "add_to_cart", 
            :car => car.attributes %>

But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).

Solution 4 - Ruby on-Rails

You probably don't want to pass the car object as a parameter, try just passing car.id. What do you get when you inspect(params) after clicking "Add to cart"?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLilzView Question on Stackoverflow
Solution 1 - Ruby on-Railsjuanm55View Answer on Stackoverflow
Solution 2 - Ruby on-RailsJonathan LeungView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMattMcKnightView Answer on Stackoverflow
Solution 4 - Ruby on-RailsbensieView Answer on Stackoverflow