【问题标题】:No Routing error when trying to add custom action to a resource尝试向资源添加自定义操作时没有路由错误
【发布时间】:2012-11-07 16:42:58
【问题描述】:

我正在尝试向资源添加自定义操作,但出现路由错误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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 那也没用。耙路线显示此products/list/up(.:format) products#product_list
    • @katie 这不是你想要的吗?要使用/products/list/up URL 触发您的products#product_list 操作?
    • 是的,但仍然给我No route matches [GET] "/products/list/up"
    • @katie 我尝试了我在虚拟应用程序上发布的 sn-p。有效!也许您只需要重新启动您的应用程序,或者您没有从您的 routes.rb 中删除一些旧代码?
    • 为了简单起见,我之前没有提到,我在路由中使用范围,现在我得到未初始化的常量 Api::V1::Api 而我的控制器在 Api::V1 下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多