如何通过link_to helper从rails视图中将参数传递给控制器​​操作 [英] How to pass a parameter to controller action from view in rails through link_to helper

查看:38
本文介绍了如何通过link_to helper从rails视图中将参数传递给控制器​​操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的 link_to 助手.

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

I want to attach a parameter in this link_to tag 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?

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

推荐答案

  1. 不要在 Rails 中的变量名和方法名中使用驼峰式大小写.这不是惯例,稍后会咬你.

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

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

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

对于你的问题,假设你的命名路径是home_connect_to_path,那么

For your question, suppose your named path is home_connect_to_path, then

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

链接看起来像

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

然后在控制器中获取它

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

这篇关于如何通过link_to helper从rails视图中将参数传递给控制器​​操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆