Kri*_*son 7 routes ruby-on-rails-3
我在rails中有一组API路由,如下所示
namespace "api" do
namespace "v1" do
resources :users do
resources :posts
resources :likes
...
end
end
end
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.我可以GET/api/v1/users/fred_flintstone并检索该用户的所有信息.
我现在要做的是添加"我"(ala facebook)的概念,这样如果用户通过身份验证(fred_flintstone),我还可以执行以下操作
GET/api/v1 /我
GET/api/v1/me/posts
...
我需要两套路线.所以我想使用GET/api/v1/me/posts或GET/api/v1/users/fred_flintstone/posts来获得相同的结果.
我已经完成了路线教程并且已经使用Google搜索,因此指针会像直接答案一样受到赞赏.
编辑:
我所做的工作非常有意义.我使用范围在routes表中创建了第二组条目:
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
Run Code Online (Sandbox Code Playgroud)
然后我添加了一个set_user方法来测试params [:user_id]的存在.我真的在寻找一种干涸的方法.
将路由保留在您的帖子中的方式,然后在控制器中解决这个问题怎么样?
这before_filter是您可以应用于User从 a中提取 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
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器函数中,您可以只使用@user变量而不必担心用户是否传递了user_id, 或me.
希望有帮助!:)
编辑:
根据您的评论,让我再试一次。
列出您希望通过标准路由和/me路由访问的所有资源的函数如何。然后您可以在您需要的两个命名空间中使用该函数。
# 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' }
Run Code Online (Sandbox Code Playgroud)