简体   繁体   English

如何通过link_to helper从rails中的视图传递参数到控制器操作

[英]How to pass a parameter to controller action from view in rails through link_to helper

<%= link_to "Connect", {controller:"home", action:"connectTo"}, id: "btny" %>

This is my link_to helper in view. 这是我在视图中的link_to帮助器。

I want to attach a parameter in this link_to tag so that I can get it in the action connectTo . 我想在这个link_to标签中附加一个参数,以便我可以在动作connectTo获取它。 I'm unable to find correct syntax or way to do it, and unable to understand some answers I found on stackoverflow. 我无法找到正确的语法或方法,并且无法理解我在stackoverflow上找到的一些答案。 How can I achieve this? 我怎样才能做到这一点?

def connectTo 
  #here i want to get the parameter i pass from link_to from view...
end
  1. Do not use camel case in variable names and method names in Rails. 不要在Rails中的变量名和方法名中使用camel case。 That's not a convention and will bite you later. 这不是一个惯例,会在以后咬你。

  2. Use named path when you can, instead of manually assign controller and action. 尽可能使用命名路径,而不是手动分配控制器和操作。

For your question, suppose your named path is home_connect_to_path , then 对于您的问题,假设您的命名路径是home_connect_to_path ,那么

link_to "Connect", home_connect_to_path(foo_param: 'bar_value')

The link will look like 链接看起来像

http://localhost:3000/home/connect_to?foo_parms=bar_value

Then get it in controller 然后在控制器中获取它

def connect_to
  foo = params[:foo_param] # 'bar_value'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM