How to get parentRecord id with ember data

99封情书 提交于 2019-12-12 02:54:15

问题


According to the test implemented in ember-data, when we request child records from hasMany relationship, the store makes a get GET to child resources url and send the ids of needed child resources.

test("finding many people by a list of IDs", function() {
  store.load(Group, { id: 1, people: [ 1, 2, 3 ] });

  var group = store.find(Group, 1);

  equal(ajaxUrl, undefined, "no Ajax calls have been made yet");

  var people = get(group, 'people');

  equal(get(people, 'length'), 3, "there are three people in the association already");

  people.forEach(function(person) {
    equal(get(person, 'isLoaded'), false, "the person is being loaded");
  });

  expectUrl("/people");
  expectType("GET");
  expectData({ ids: [ 1, 2, 3 ] });

How can I also send the id of the parent record (Group) ? My server need this id to retrieve the embbeded record. It need something like :

expectData({groud_id: the_group_id, ids: [1,2,3] })

回答1:


You have no way to pass additional parameters, and as of today, resources are expected to be 'at root'. It means, in your config/routes.rb:

resources :organization
resources :groups
resources :people

You could be scared at first sight, "OMG, I am loosing data isolation...", but in fact this isolation is finally usually provided by relational joins, starting from an ancestor owning nested stuff. Anyway, these joins can be performed by the ORM, at the (reasonable) price to declare any leaf resource in the ancestor.

Assuming you are using RoR, you can add relational shortcuts in your models to ensure nested resources isolation like that (please note the has_many ... through ... which is the important stuff):

class Organization < ActiveRecord::Base
  has_many :groups
  has_many :people, through: groups
end

class Group < ActiveRecord::Base
  has_many :people
end

Then in your controllers, directly use the shortcuts, flattened in your root holder model (here Organization):

class GroupsController < ApplicationController
  def index
    render json: current_user.organization.groups.all, status: :ok
  end
end

class PeopleController < ApplicationController
  def index
    render json: current_user.organization.people.all, status: :ok
  end
end

(Here, the whole sets of existing instances is returned for better clarity. Result should be filtered according to the requested ids...)



来源:https://stackoverflow.com/questions/10385430/how-to-get-parentrecord-id-with-ember-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!