在窗口上创建带有红宝石点的错误路线

时间:2017-04-05 03:04:30

标签: ruby-on-rails ruby windows

我在windows上的ruby中是新的..我正在尝试使用方法的链接,但它给了我http://localhost:3000/products.2(expecting http://localhost:3000/products/2)。我读了一些关于这个问题的论坛,我读到的答案之一(source)是

"Have you try tweet_path and user_path ?

You want to access the show action. For that action, the model name must be singular in the *_path call."

查看

<html>
<head>
    <title>MY STORE!</title>
</head>
<body>
    <h1><align="center"> WELCOME TO MY STORE</h1>
    <table border = "1" width="100%">
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Size</td>
            <td>Price</td>
            <td>Created At</td>
            <td>Updated At</td>
            <td>Action</td>
        </tr>
        <% @product.each do |p| %>

        <tr>
            <td><%= p.id %></td>
            <td><%= p.name %></td>
            <td><%= p.size %></td>
            <td><%= p.price %></td>
            <td><%= p.created_at.strftime("%B, %d, %Y") %></td>
            <td><%= p.updated_at %></td>
            <td><%= link_to 'View', products_path(p) %></td>
        </tr>
        <% end %>

    </table>
</body>
</html>

注意:我尝试将此单数&lt;%= link_to&#39; View&#39;,product_path(p)%&gt;它给了我一个错误

NoMethodError in Products#index

undefined method `product_path' for #<#<Class:0x9955218>:0x4ca3b98>
Did you mean?  products_path
<td><%= p.created_at.strftime("%B, %d, %Y") %></td>
            <td><%= p.updated_at %></td>
            <td><%= link_to 'View', product_path(p) %></td> // to this line
        </tr>
        <% end %>

路线

Rails.application.routes.draw do
  get 'products/' => 'products#index'
  get 'products/:id' => 'products#show'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

控制器

class ProductsController < ApplicationController
  def index
    @product = Product.all.order('created_at DESC')

  end
  def show
    @post = Product.find(params[:id])


  end

end

2 个答案:

答案 0 :(得分:1)

尝试更改路线:

get 'products/' => 'products#index'
get 'products/:id' => 'products#show'

要:

resources :products

答案 1 :(得分:1)

实际上这里的主要问题是以下路由不会生成路由助手

get 'products/' => 'products#index'
get 'products/:id' => 'products#show'

所以,即使网址和控制器都是正确的,您也无法使用product_path方法

使用它有两种方法

resources :products, only: [:index, :show]

get 'products/' => 'products#index', as: 'products'
get 'products/:id' => 'products#show', as: 'product'

现在您可以使用products_pathproduct_path(10)