Ruby-on-rails 如何通过link_to helper从rails视图中将参数传递给控制器​​操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19770052/
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:59:36  来源:igfitidea点击:

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

ruby-on-railsruby-on-rails-3.1

提问by Billy Chan

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

This is my link_tohelper in view.

这是我link_to眼中的帮手。

I want to attach a parameter in this link_totag so that I can get it in the action connectTo. I'm unable to find correct syntax or way to do it, and unable to understand some answers I found on stackoverflow. How can I achieve this?

我想在这个link_to标签中附加一个参数,以便我可以在 action 中获取它connectTo。我无法找到正确的语法或方法,也无法理解我在 stackoverflow 上找到的一些答案。我怎样才能做到这一点?

def connectTo 
  #here i want to get the parameter i pass from link_to from view...
end

回答by Billy Chan

  1. Do not use camel case in variable names and method names in Rails. That's not a convention and will bite you later.

  2. Use named path when you can, instead of manually assign controller and action.

  1. 不要在 Rails 中的变量名和方法名中使用驼峰式大小写。这不是约定俗成的,以后会咬你的。

  2. 尽可能使用命名路径,而不是手动分配控制器和操作。

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'