如何使用ember数据获取parentRecord id

时间:2012-04-30 14:32:09

标签: ember.js ember-data

根据在ember-data中实现的测试,当我们从hasMany关系请求子记录时,商店会获得对子资源URL的GET并发送所需子资源的ID。

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 ] });

我怎样才能发送父记录(组)的ID?我的服务器需要此ID来检索嵌入记录。它需要类似的东西:

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

1 个答案:

答案 0 :(得分:1)

您无法传递其他参数,截至今天,资源预计将“在根”。这意味着,在config/routes.rb

resources :organization
resources :groups
resources :people

你可能一见钟情,“OMG,我正在失去数据隔离......”但实际上这种隔离最终通常由关系连接提供,从拥有嵌套东西的祖先开始。无论如何,这些连接可以由ORM以(合理的)价格执行,以声明祖先中的任何叶子资源。

假设您正在使用RoR,您可以在模型中添加关系快捷方式,以确保嵌套资源与隔离(请注意 has_many ... through ... 这是重要的东西)

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

class Group < ActiveRecord::Base
  has_many :people
end

然后在您的控制器中,直接使用在根持有者模型中展平的快捷方式(此处 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

(这里,为了更清晰,返回整个现有实例集。应根据请求的ID过滤结果...)