【问题标题】:Is there a way to get a url for a resource in rails有没有办法在rails中获取资源的url
【发布时间】:2015-10-18 11:30:16
【问题描述】:

如果我有 @post 之类的资源,有没有办法获取指向该资源路径的 url,例如:

@post.to_url
url_for(@post)
path_to(@post)
@post.to_path...

你得到了理想

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    给定一个像@post 这样的资源,url_for 将返回路径。

    url_for(@post) #=> "/posts/1"
    

    从控制台:

    app.url_for(@post) #=> "http://www.example.com/posts/1"
    app.post_path(@post) #=> "/posts/1"
    

    见:

    【讨论】:

    • 它在 Rails 控制台中不起作用。那是因为我需要包含 ActionController 之类的东西吗?
    • 在 Rails 控制台中,使用app.url_for(@post)
    • 太棒了!谢谢@mysmallidea
    • 如何在模型中使用它?
    • 我通过 include Rails.application.routes.url_helpers 得到了它
    猜你喜欢
    • 2019-04-22
    • 2017-04-07
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多