Ember Data Nested Resource URL

Let's say I have a Rails application with the following layout (this simplified my actual project a bit):

User
    has many Notes

Category
    has many Notes

Note
    belongs to User
    belongs to Category

Notes can be obtained:

/users/:user_id/notes.json
/categories/:category_id/notes.json

but not:

/notes.json

Too many notes throughout the system to send on one request is the only viable way - to send only the necessary notes (i.e. notes belonging to the user or categories that the user is trying to view).

What would be my best way to implement this with Ember Data?

+5
source share
1 answer

I would simply say:

Ember Models

App.User = DS.Model.extend({
  name: DS.attr('string'),
  notes: DS.hasMany('App.Note')
});

App.Category = DS.Model.extend({
  name: DS.attr('string'),
  notes: DS.hasMany('App.Note')
});

App.Note = DS.Model.extend({
  text: DS.attr('string'),
  user: DS.belongsTo('App.User'),
  category: DS.belongsTo('App.Category'),
});

Rails Controllers

class UsersController < ApplicationController
  def index
    render json: current_user.users.all, status: :ok
  end

  def show
    render json: current_user.users.find(params[:id]), status: :ok
  end
end

class CategoriesController < ApplicationController
  def index
    render json: current_user.categories.all, status: :ok
  end

  def show
    render json: current_user.categories.find(params[:id]), status: :ok
  end
end

class NotesController < ApplicationController
  def index
    render json: current_user.categories.notes.all, status: :ok
    # or
    #render json: current_user.users.notes.all, status: :ok
  end

  def show
    render json: current_user.categories.notes.find(params[:id]), status: :ok
    # or
    #render json: current_user.users.notes.find(params[:id]), status: :ok
  end
end

: ( ,...). parentRecord ember .

class ApplicationSerializer < ActiveModel::Serializer
  embed :ids, include: true
end

class UserSerializer < ApplicationSerializer
  attributes :id, :name
  has_many :notes
end

class CategorySerializer < ApplicationSerializer
  attributes :id, :name
  has_many :notes
end

class NoteSerializer < ApplicationSerializer
  attributes :id, :text, :user_id, :category_id
end

, , include false ApplicationSerializer.


, ember- , .

+5

All Articles