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

自闭症网瘾萝莉.ら 提交于 2019-12-03 12:47:36

问题


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

This is my link_to helper in view.

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:


  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.

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

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'


来源:https://stackoverflow.com/questions/19770052/how-to-pass-a-parameter-to-controller-action-from-view-in-rails-through-link-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!