简体   繁体   English

如何使用RABL为嵌套资源建模?

[英]How to model nested resources using RABL?

I want to setup a nested route in my Rails project as illustrated here: 我想在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

I use RABL templates to render JSON contents. 我使用RABL模板来呈现JSON内容。 It might be that I misunderstand the purpose of child elements in RABL. 这可能是我误解的目的, child在Rabl的元素。 As far as I understand they will not lead me to a RESTful path as show below. 据我了解,它们不会将我引向RESTful路径,如下所示。 On the other hand please tell me if RABL does not support nested resources. 另一方面,请告诉我RABL是否不支持嵌套资源。

How can I output JSON for a nested route such as ... ? 如何为诸如...之类的嵌套路由输出JSON? How can I write a RABL template which matches the route users/:id/places ? 如何编写与路线users/:id/places相匹配的RABL模板?

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

I do not want to display the user information. 不想显示用户信息。 It should not be possible to retrieve user data via the following paths: 应该是可能通过以下途径来获取用户数据:

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

In the project I use CanCan 1.6.9. 在项目中,我使用CanCan 1.6.9。 and Devise 2.2.3. 设计2.2.3。

I've implemented something similar using before filters in the controller. 我已经在控制器中使用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

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

collection @places
attributes :id, :name, etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM