【问题标题】:Custom routes with Rails API使用 Rails API 自定义路由
【发布时间】:2013-05-25 03:54:47
【问题描述】:

我正在使用 Rocket_Pants gem 为我现有的 Rails 应用程序提供 API 访问权限。我的路线中有以下内容:

  # HTTP routing 
  resources :posts do
    collection do
      get 'search'
    end
  end

  # API routing
  api :version => 1 do
    resources :posts, :only => [:index, :show]
    resources :posts do
      collection do
        get 'search'
      end
    end
  end

我对@9​​87654322@ 和post/:id works 的json API 请求。但是,对 localhost:3000/1/posts/search?query=my_query 的 json API 查询不会。

(注意:对localhost:3000/posts/search?query=my_query 的http 请求有效)。

我应该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails rails-routing


    【解决方案1】:

    我认为您不应该在 api 块内多次重新定义 :posts 资源。

    api :version => 1 do
      resources :posts, only: [:index, :show] do
        collection do
          get 'search'
        end
      end
    end
    

    【讨论】:

    • 您的解决方案似乎有效(即,我遇到了不同的错误)。你能解释一下为什么多次定义:posts会导致麻烦吗?
    • 我对 Rails 路由内部的了解还不够,无法给你一个可靠的答案。 here 是方法定义。我可以告诉你的是,这样的多重定义是不必要且不整洁的;仅凭这两个原因不这样做。如果路由映射器也不允许这样做,那么更有理由清理您的代码:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多