通过 link_to ruby​​ on rails 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1898737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:02:25  来源:igfitidea点击:

pass parameter by link_to ruby on rails

ruby-on-railsparameters

提问by Lilz

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?

当我在 add_to_cart 方法中时...我该如何调用 :car 呢?

@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.

顺便说一下,汽车是我的汽车对象。

回答by juanm55

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

其中,将在您的数据库中的“汽车”表(如 rails 复数形式)中找到 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

一年多后,但如果你看到它或任何人看到它,我可以使用积分;D

回答by Jonathan Leung

The above did not work for me but thisdid

上面并没有对我来说有效,但这个确实

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

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

回答by MattMcKnight

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).

但我真的很想看看汽车对象在哪里设置这个页面(即视图的其余部分)。

回答by bensie

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

您可能不想将car对象作为参数传递,请尝试仅传递car.id. inspect(params)单击“添加到购物车”后会得到什么?