Rails 4 - 通过link_to传递参数?

时间:2013-07-17 17:36:28

标签: ruby-on-rails

我有一个表单 - 根据用户点击显示表单的链接,我希望将不同的隐藏参数传递给记录并在提交时保存。有一个很好的方法来做到这一点?提前谢谢!

例如:

<%= link_to 'General Request', new_request_path %>

<%= link_to 'Project Request', new_request_path %> ### -> set request.project = true

<%= link_to 'Administrative Request', new_request_path %>  ### -> set request.admin = true

2 个答案:

答案 0 :(得分:9)

对于您的示例,您可以使用:

<%= link_to 'Project Request', new_request_path(project: true) %>

会产生http://127.0.0.1:3000/request?project=true

之类的链接

<%= link_to 'Administrative Request', new_request_path(admin: true) %>

会产生http://127.0.0.1:3000/request?admin=true

之类的链接

答案 1 :(得分:2)

我认为有两种方法可以完成你想要做的事情。

  1. 创建3条不同的路由来完成不同类型的请求。例如,new_request_pathnew_project_request_pathnew_admin_request_path

  2. 如果您要申请新项目,请使用<%= link_to 'Project Request', new_request_path(:request_type => 'project') %>。在控制器中,您可以处理不同的请求类型。

  3. def new
      case params[:request_type]
      when 'general'
        do_something
      when 'project'
        do_something_1
      when 'admin'
        do_something_else
      end
    
      ...
    end