8

我在 Rails 中有一组 API 路由,如下所示

namespace "api" do
   namespace "v1" do
     resources :users do
       resources :posts
       resources :likes
       ...
     end
   end
end

到目前为止,一切都很好。我可以 GET /api/v1/users/fred_flintstone 并检索该用户的所有信息。

我现在想做的是添加“我”(ala facebook)的概念,这样如果用户经过身份验证(fred_flintstone),我还可以执行以下操作

获取 /api/v1/我

获取 /api/v1/me/posts

...

我需要两组路线。所以我想使用 GET /api/v1/me/posts 或 GET /api/v1/users/fred_flintstone/posts 来获得相同的结果。

我已经完成了路线教程,并在谷歌上搜索过,因此指针将与直接答案一样受到赞赏。

编辑:

我所做的很有效。我使用范围在路由表中创建了第二组条目:

scope "/api/v1/me", :defaults => {:format => 'json'}, :as => 'me' do
  resources :posts, :controller => 'api/v1/users/posts'
  resources :likes, :controller => 'api/v1/users/likes'
  ...
end

然后我添加了一个 set_user 方法来测试 params[:user_id] 的存在。我真的在寻找一种方法来干燥它。

4

1 回答 1

5

将路由保留在您的帖子中的方式,然后在控制器中解决这个问题怎么样?

Heres abefore_filter您可以将其应用于您拥有的User从 a中提取 a 的所有路线:user_id

# Set the @user variable from the current url; 
# Either by looking up params[:user_id] or
# by assigning current_user if params[:user_id] = 'me'
def user_from_user_id
  if params[:user_id] == 'me' && current_user
    @user = current_user
  else
    @user = User.find_by_user_id params[:user_id]
  end

  raise ActiveRecord::RecordNotFound unless @user
end

然后在您的控制器函数中,您可以只使用该@user变量而不必担心用户是否传递了 auser_idme.

希望有帮助!:)

编辑:

鉴于您的评论,让我再拍一张。

一个功能如何列出您希望通过标准路由和/me路由访问的所有资源。然后,您可以在所需的两个命名空间中使用该函数。

路线.rb

# Resources for users, and for "/me/resource"
def user_resources
  resources :posts
  resources :likes
  ...
end

namespace 'api' do
   namespace 'v1' do
     resources :users do
       user_resources
     end
   end
end

scope '/api/v1/:user_id', :constraints => { :user_id => 'me' },
                          :defaults => {:format => 'json'}, :as => 'me' do
  user_resources
end

# We're still missing the plain "/me" route, for getting
# and updating, so hand code those in
match '/api/v1/:id' => 'users#show', :via => :get,
                                     :constraints => { :id => 'me' }                
match '/api/v1/:id' => 'users#update', :via => :put,
                                       :constraints => { :id => 'me' }
于 2012-04-14T04:37:16.007 回答