【问题标题】:Rails Routing: can't get helper route function to workRails 路由:无法让辅助路由功能工作
【发布时间】:2017-03-27 23:31:01
【问题描述】:

我无法弄清楚让辅助路径起作用的魔力。我的用例是这样的:“mydomain/articles/some_slug”用于带有显示操作的文章控制器。给定的 URL 完美运行。但我不知道如何让 rails 的助手在这种情况下工作。

routes.rb:

  get '/articles/:slug',    to: 'articles#show', as: 'article'

   --- or ---

  get '/articles/:slug',    to: 'articles#show'

   --- or changing :slug to :id

rails 路线(这个和类似的变化与其他 --- 或 --- 条件):

  articles GET    /articles/:slug(.:format)                 articles#show

我收到未定义的方法“path_to_article”错误。在以下情况下会发生此错误:

我的.html.erb:

  <%= path_to_article(locals[:article]) %>

   --- or ---

  <%= path_to_article(id: locals[:article].slug) %>

   --- or ---

  <%= path_to_article(slug: locals[:article].slug) %>

然而,这段代码运行良好,但我不喜欢它,这正是我想要避免的:

<a href="/articles/<%= locals[:article].slug %>">

我还尝试了复数和非复数组合,我可以在这些组合中以及几乎可以在网上提出或找到的任何其他随机想法。最后,我似乎无法弄清楚如何让rails 识别'path_to_article()'。

Rails 5.0.2

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails routes helpers


    【解决方案1】:
    rails routes
    

    返回:

    • 路线名称(如果有)
    • 使用的 HTTP 动词(如果路由没有响应所有动词)
    • 要匹配的 URL 模式
    • 路由的路由参数

    见: http://guides.rubyonrails.org/routing.html#listing-existing-routes

    基本上,您应该在视图中将 _path 附加到路由名称以调用路由助手。

    在您的情况下,路由名称是 articles,因此辅助方法是 articles_path。

    【讨论】:

    • 我今天打开了该指南,好吧,我想我在小细节上花了太多时间,而我错过了明显的东西。我对 path_to_xxx 如此着迷,以至于我有隧道视野。感谢您的帮助。
    【解决方案2】:

    你想使用:

    articles_path(locals[:article])
    

    或

    articles_path(locals[:article].slug)
    

    取决于您的设置方式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多