Tôi có thể nói đơn giản:
mô hình
Ember
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 điều khiển
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
Hãy cẩn thận: các bộ điều khiển là một phiên bản đơn giản (chỉ số có thể lọc theo để yêu cầu id, ...). Bạn có thể xem How to get parentRecord id with ember data để thảo luận thêm.
kích hoạt mẫu 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
Chúng tôi bao gồm dữ liệu sideload ở đây, nhưng bạn có thể tránh nó, thiết lập các thông số include
-false
trong ApplicationSerializer
.
Người sử dụng, danh mục & ghi chú sẽ được nhận & cache của ember dữ liệu khi họ đến, và các mặt hàng thiếu sẽ được yêu cầu khi cần thiết.
Liệu dữ liệu Ember có tự động yêu cầu sử dụng URL thích hợp không (/users/:user_id/notes.json hoặc /categories/:category_id/notes.json) chỉ dựa trên liên kết? – user1539664
Không, nó sẽ sử dụng '/ notes', nhưng bộ điều khiển của bạn sẽ đảm bảo tham gia, truyền tải mối quan hệ bắt đầu từ (danh mục | người dùng), vì vậy tập dữ liệu sẽ chỉ giới hạn trong các trường hợp hữu ích. –
Vì vậy, không có cách nào cho phép truy cập vào các ghi chú từ cả thể loại và đối tượng người dùng? –