【问题标题】:Rails named route & helper (/controller/:id/randomname)Rails 命名路由和助手 (/controller/:id/randomname)
【发布时间】:2015-09-19 08:01:57
【问题描述】:

我正在尝试使以下路由正常工作:

get 'items/:id/pictures' => 'pictures#show'

我应该使用什么样的辅助方法?使用<%= link_to pictures_item_path do %> 我得到以下错误:

undefined local variable or method `pictures_item_path' for #<#<Class:0x007fa2c6181710>:0x007fa2c40ba7c0>

我尝试使用get 'items/:id/pictures' =&gt; 'pictures#show', as: 'items/:id/pictures',但出现以下错误:

Invalid route name: 'items_:id_pictures'

【问题讨论】:

    标签: ruby-on-rails-4 routes helper


    【解决方案1】:

    你的路线是正确的。如果你要使用助手,你必须使用Named routes

    可以通过传递 :as 选项来命名路由,以便在您的源中轻松引用完整 URL 的 name_of_route_url 和 URI 路径的 name_of_route_path

    # In routes.rb
    get '/login', to: 'accounts#login', as: :login
    
    # With render, redirect_to, tests, etc.
    redirect_to login_url
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      routes.rb

      get 'items/:id/pictures' => 'pictures#show'
      

      在控制台执行此命令

      rake routes
      

      你会得到这样的结果

      pictures_item GET    /items/:id/pictures(.:format)   pictures#show
      

      你必须使用pictures_item_path(:id)pictures_item_url(:id),因为它是成员路由

      试试这个:

      <%= link_to 'item picture', pictures_item_path(@item_id) %>
      

      阅读更多关于routes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 1970-01-01
        相关资源
        最近更新 更多