【问题标题】:Ruby on Rails get paramenter from URL on ViewRuby on Rails 从 View 上的 URL 获取参数
【发布时间】:2016-11-16 18:41:02
【问题描述】:

我想从我的视图/html 上的 URL 中获取参数。

例如,我正在显示我的数据库中的特定项目,并且 URL 是这样的:“http://localhost:3000/menus/index.%23%3CMenu::ActiveRecord_Relation:0x007f50ed153250%3E?id=6

我想要的是:当我单击该特定项目的新按钮时,表单会打开 URL“http://localhost:3000/menus/new”,但我想以某种方式将该 id=6 传递给这个新视图。

我在 html 上使用此代码打开表单:<%= link_to 'Novo', new_menu_path %>

我也试过:<%= link_to 'Novo', new_menu_path(@menus, :id) %>,但 id 参数始终为 null/空。

我该怎么做? 谢谢

【问题讨论】:

    标签: ruby-on-rails ruby rubygems


    【解决方案1】:

    在定义 link_to 时向 url 传递一个额外的参数

    <%= link_to 'Novo', new_menu_path(id: @menu.id, other_param: "hello") %>
    

    将生成http://localhost:3000/menus/new?id=6&amp;other_param=hello

    这会将以下内容添加到 params 哈希中

    Parameters: {"id"=>"6", "other_param"=>"hello"}
    

    【讨论】:

      【解决方案2】:

      :id 只是一个符号,你需要告诉路由助手绑定什么。例如

      <%= link_to 'Novo', new_menu_path(id: params[:id]) %>
      

      应该会给你类似/menus/new?id=6的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        • 1970-01-01
        • 2023-03-04
        • 2015-10-26
        • 1970-01-01
        • 2012-06-30
        • 1970-01-01
        相关资源
        最近更新 更多