【问题标题】:Undefined method ` _path' on Show action of nested resources显示嵌套资源操作的未定义方法`_path'
【发布时间】:2017-05-08 00:11:26
【问题描述】:

我是一名 Rails 新手。

我在我的第一个 rails 应用程序上做了一些路由更改,在这个应用程序中你可以创建国会和每个 has_many 类别,每个类别 belongs_to(只有一个)国会,所以,我的路线看起来像这样:

  resources :congresses do
    resources :categories do
      resources :presentations
    end
   resources :news
  end  

我更改了类别视图的一些内容,所以,link_to 现在是congress_category_path 的形式,这些链接就像一个魅力。之后,我在form_for 类别上添加[@congress, @category],因此,该应用程序允许您创建一个类别。这是我的问题开始的地方......

在这部分视图:

  <tbody>
<% Congress.find(params[:congress_id]).categories.each do |category| %>
  <tr>
    <td><%= category.name %></td>
    <td><%= category.description %></td>
    <td><%= category.presentations %></td>
    <td><%= link_to 'Show', category %></td>
    <td><%= link_to 'Edit', edit_congress_category_path(category) %></td>
    <td><%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

每个类别都是一个实例,&lt;%= link_to 'Show', category %&gt; 提取 category_path 而不是 congress_category_path...我在哪里可以更改该特定路线?

这给了我一个

未定义方法category_path 用于#&lt;#&lt;Class:0x9961e00&gt;:0x929a360&gt;

我什至尝试过类似的东西

congress_category_path ([@congress, category])

但这也没用

非常感谢您的帮助,谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby routes ruby-on-rails-5


    【解决方案1】:

    看来你的语法有误。

    从这里:http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects,您可以选择从嵌套资源中构建路径:

    congress_category_path(@congress, category)
    

    或 (注意 _path 方法不接受数组参数)

    url_for([@congress, category])
    

    (而 url_for 方法可以)。

    如果有帮助,请告诉我!

    【讨论】:

      【解决方案2】:

      几句话

      1。限制资源深度

        resources :congresses do
          resources :categories do
            resources :presentations
          end
        end 
      

      指南不建议使用过于嵌套的路由。相反,您可能想看看shallow routes

      2 如何构建路径助手

      接下来你需要明白这一点

      resources :congresses do
        resources :categories
      end
      

      生成以下格式的 CRUD 路由(#show 的示例)

      GET /congresses/:congress_id/categories/:id => congresses/categories_controller#show
      

      你可以看到这个“路由”有两个参数congress_idid,所以Rails生成的路径助手可以接受两个位置参数congress_idid,路径助手应该写成这样的

      congress_category_path(@congress, category)
      

      注意:它有点相当于

      congress_category_path(congress_id: @congress.id.to_s, id: category.id.to_s)
      

      3 使用浅层路线可以使用简单路线

      # config/routes.rb
      resources :congresses do
        resources :categories, shallow: true
      end
      
      # views/your_view.html.erb
      <%= link_to 'Show', category %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-29
        • 2014-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多