【问题标题】:How to get parentRecord id with ember data如何使用 ember 数据获取 parentRecord id
【发布时间】:2012-04-30 14:32:09
【问题描述】:

根据ember-data中实现的测试,当我们从hasMany关系中请求子记录时,store对子资源url进行get 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] })

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    您无法传递其他参数,并且从今天开始,资源预计将位于“根目录”。这意味着,在你的config/routes.rb

    resources :organization
    resources :groups
    resources :people
    

    第一眼你可能会害怕,“天啊,我正在失去数据隔离......”,但实际上这种隔离最终通常是由关系连接提供的,从拥有嵌套内容的祖先开始。无论如何,这些连接可以由 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 过滤结果...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      相关资源
      最近更新 更多