【问题标题】:Rails Routing SetupRails 路由设置
【发布时间】:2012-03-10 18:47:43
【问题描述】:

我在 Rails 3.0.x 应用程序中遇到路由问题。

我想要实现的是像 /registration/renew/1 这样的 URL。这个想法是,这将为 id = 1 的成员更新注册。

为此,我设置了以下路线

routes.rb

match "registration/renew" => "registration#renew"

用户通过导航链接如

到达注册页面
<%= link_to "Full Member", registration_renew_path(@member)  %>

问题在于生成的链接类似于:/registration/renew.1,这表明正在创建和附加 :format 扩展。然后我尝试根据以下匹配规则通过包含 responder 参数 :format 来使其成为可选

match "registration/renew(/:id(.:format))" =&gt; "registration#new"

但这失败了

No route matches {:controller=&gt;"registration", :action=&gt;"renew", :format=&gt;#&lt;Member id: 1,.....

所以此时我重新检查了 Rails 指南等,但仍然无法生成我想要的 URL。

只有当我有两个规则时:

match "registration/renew" => "registration#renew"
match "registration(/:action(/:id(.:format)))" => "registration#renew"

在路由文件中,URL /registration/renew/1 会将我带到该页面。虽然我觉得这不是正确、整洁的解决方案。

最后的问题

  1. 应该是什么link_to方法
  2. 什么是正确的 routes.rb 条目

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-routing


    【解决方案1】:

    您只需要显式传递参数并定义此路由的名称

    match "registration(/:action(/:id(.:format)))" => "registration#renew", :as => registration_renew
    

    只有身份证

    <%= link_to "Full Member", registration_renew_path(:id => @member.id)  %>
    

    有id和格式

    <%= link_to "Full Member", registration_renew_path(:id => @member.id, :format => :xml)  %>
    

    没有身份证

    <%= link_to "Full Member", registration_renew_path  %>
    

    在您的示例中,您不需要没有参数的路线。

    【讨论】:

      【解决方案2】:

      你可以在link_to方法中提及控制器和动作

      <%=link_to "Full Member", :controller => "registration", :action => "renew", :id => @member.id %> 
      

      更多选项请参考以下教程。

      http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

      【讨论】:

        猜你喜欢
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 2014-08-28
        • 2013-01-12
        • 2018-03-13
        相关资源
        最近更新 更多