【问题标题】:How to model nested resources using RABL?如何使用 RABL 对嵌套资源进行建模?
【发布时间】:2013-06-19 12:19:57
【问题描述】:

我想在我的 Rails 项目中设置一个嵌套路由,如下所示:

# config/routes.rb
DemoApp::Application.routes.draw do
  namespace :api, defaults: {format: :json} do
    namespace :v1 do
      resources :places, only: [:index]
      resources :users do
        resource :places
      end
    end
  end
  devise_for :users, controllers: { sessions: "sessions" }
  ActiveAdmin.routes(self)
end

我使用RABL templates 来呈现 JSON 内容。可能是我误解了RABL 中child 元素的用途。据我了解,它们不会将我引向如下所示的 RESTful 路径。另一方面,如果 RABL 不支持嵌套资源,请告诉我。

如何为嵌套路由输出 JSON,例如 ... ?如何编写匹配路由users/:id/places的RABL模板?

http://localhost:3000/api/v1/users/13/places.json

我确实想要显示用户信息。应该可以通过以下路径检索用户数据:

http://localhost:3000/api/v1/users/13.json
http://localhost:3000/api/v1/users.json

在项目中我使用CanCan 1.6.9.Devise 2.2.3.

【问题讨论】:

    标签: ruby-on-rails json nested-resources rabl view-templates


    【解决方案1】:

    我在控制器中使用 before 过滤器实现了类似的功能。

    class Api::PlacesController < ApplicationController
    before_filter :find_user
    
    def index
        if @user 
            @places = @user.places
        else
            ...    
        end
    end
    
    private
    
    def find_user
        @user = User.find(params[:user_id]) if params[:user_id]
    end
    

    然后在 api/places/index.json.rabl

    collection @places
    attributes :id, :name, etc
    

    【讨论】:

    • 但这真的提供了users/:id/places这样的嵌套路由吗?我不想覆盖 index 操作的默认行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    相关资源
    最近更新 更多