如何使用带有参数的Rails命名路由助手? [英] How to use Rails named route helpers with parameters?

查看:63
本文介绍了如何使用带有参数的Rails命名路由助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此路线

match 'posts/hello/:name/:title' => 'post#show', :as => :hello




  • 我可以用什么方式称呼 hello_path

    如果我呼叫 hello_path(@post),它会尝试做什么?

    if i call hello_path(@post), what does it try to do?

    我希望:name :title 文件将自动绑定到路径,但似乎Rails只知道如何从模型对象中获取:id。

    I was hoping that the :name and :title files will bind to the path automatically but it seems that rails only know how to get the :id out of the model object.

    相反,它只有在我这样称呼的情况下才能起作用

    instead, it only works if I call it like

    <%= link_to "link2", hello_url(:name=> @post.name, :title=>@post.title) %>
    

    (缺少适当的文档确实使我丧命)

    (lack of proper documentation is really killing me)

    推荐答案

    回答两个问题:


    • 在命令行中,运行 rake route 查看您的应用程序
      中有哪些路由。它会显示所有使用命名路由的方法,
      只需在左侧
      上显示的路由名称上添加 _path或 _url。

    • 调用 hello_path(@post)会生成指向
      显示页面的URL hello 实例。

    • At the command line, runrake routes to see what routes there are in your app. It will show you all the ways you can use the named routes, just add "_path" or "_url" to the name of the route which is shown on the left.
    • Calling hello_path(@post) will generate a URL to the show page for that hello instance.

    您所说的方式是正常的:

    The way you are calling it is the norm:

    <%= link_to "link2", hello_url(:name=> @post.name, :title=>@post.title) %>
    

    但是,这也可能起作用:

    However, this may work too:

    <%= link_to "link2", hello_url(@post.name, @post.title) %>
    

    以下是一些文档(Rails API除外)会有所帮助。
    http://guides.rubyonrails.org/routing.html

    Here is some documentation (other than the Rails API) which should help. http://guides.rubyonrails.org/routing.html

    这篇关于如何使用带有参数的Rails命名路由助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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