powiedziałbym prosta:
modele
Ember kontrolery
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'),
});
Szyny
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
Bądź ostrożny: te sterowniki są uproszczoną wersją (indeks może filtrować według do żądanych identyfikatorów, ...). Możesz zajrzeć na How to get parentRecord id with ember data w celu dalszej dyskusji.
aktywnego modelu Serializers
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
Mamy zawierać dane sideload tutaj, ale można go uniknąć, ustawiając parametr include
do false
w ApplicationSerializer
.
Użytkowników, kategorie & notatki będą odbierane & buforowane przez Ember-danych, gdyż pochodzą, a brakujące elementy będą wymagane w razie potrzeby.
Czy dane Ember automatycznie zażądają podania odpowiedniego adresu URL (/users/:user_id/notes.json lub /categories/:category_id/notes.json) w oparciu o skojarzenie? – user1539664
Nie, użyje on '/ notes', ale kontroler zapewni łączenie, przechodzenie relacji zaczynając od (categories | users), więc zbiór danych będzie ograniczony tylko do użytecznych instancji. –
Więc nie ma możliwości dostępu do notatek z obiektów kategorii i użytkownika? –