尝试向资源添加自定义操作时出现“无路由”错误

时间:2012-11-19 17:44:00

标签: ruby-on-rails ruby-on-rails-3 rest routes

我正在尝试向资源添加自定义操作,但我收到路由错误No route matches [GET] "/products/list/up"。我试过在routes.rb中注释掉URI,但它们也不起作用。我究竟做错了什么?

我在routes.rb

中有这个
 namespace :api, :defaults =>{format: 'json'} do
 scope module:  :v1 ,constraints: ApiConstraints.new(version:1, default: true) do

resources :products do
member do
  match  "/list/up" =>"products#product_list" ,:via=>:get
  #get "/list/up" , :action=>"product_list"
  #get "/list/up" , :to=>"product_list"
end
end
 end
 end
products_controller.rb中的

def product_list
  @products= Product.all
  respond_to do |format|
    format.json { render json: @products.to_json}
  end
end

1 个答案:

答案 0 :(得分:1)

请尝试collection而不是member,因为您未在路径中提供任何id

resources :products do
    collection do # <-----<
        get  "/list/up" =>"products#product_list"
    end
end

正在运行rake routes

list_up_products GET    /products/list/up(.:format)  products#product_list
        products GET    /products(.:format)          products#index
                 POST   /products(.:format)          products#create
     new_product GET    /products/new(.:format)      products#new
    edit_product GET    /products/:id/edit(.:format) products#edit
         product GET    /products/:id(.:format)      products#show
                 PUT    /products/:id(.:format)      products#update
                 DELETE /products/:id(.:format)      products#destroy