6

给定 RESTful 服务器上的这些 JSON 数据模型

/用户

{"users":[
   {"id":"1","first_name":"John","last_name":"Doe"},
   {"id":"2","first_name":"Donald","last_name":"Duck"}
]}

/用户/1

{"user": 
   {"id":"1","first_name":"John","last_name":"Doe","account":"1"}
}

/帐户

{"accounts":[
   {"id":"1","owned_by":"1"},{"id":"2","owned_by":"2"}
]}

/帐户/1

{"account":
   {"id":"1","owned_by":"1","transactions":[1,17]}
}

以及这些 Ember 数据模型

App.Store = DS.Store.extend({
  revision: 11,
  adapter: DS.RESTAdapter.create({
    url: 'http://api.mydomain.ca'
  })
});

App.User = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    account: DS.belongsTo('App.Account')
});

App.Account = DS.Model.extend({
    ownedBy: DS.belongsTo('App.User'),
    transactions: DS.hasMany('App.Transaction')
});

我还需要编写哪些其他 ember 代码才能将数据加载到模型中,然后编写一个模板来输出用户名、帐户 ID 和帐户中的交易数量?

4

2 回答 2

3

我能够解决这个问题,所以我会发布我的代码以防它帮助其他人。诀窍是确保 JSON 数据的格式与 Ember 想要的完全一致,并创建正确的路由。

据我所知,Ember 期望父对象提供子对象列表。这对我来说感觉很奇怪,所以如果有人知道用外键引用其父母的子对象的方法,请告诉我。

我将 /user/:user_id JSON 对象上的帐户属性更改为 account_id 我还在 /users 中找到的用户对象中包含了 account_id,并将帐户上的 own_by 属性更改为 user_id。

我的 javascript 文件

var App = Ember.Application.create();

// Router
App.Router.map(function() {
    this.resource('users', function() {
        this.resource('user', {path:':user_id'});
    }); // '/#/users/:user_id'
    this.resource('accounts', function() {
        this.resource('account', {path:':account_id'});
    });
});

App.IndexRoute = Ember.Route.extend({
    redirect: function() {
        this.transitionTo('users');
    }
});

App.UsersRoute = Ember.Route.extend({
    model: function() {
        return App.User.find();
    }
});

App.AccountsRoute = Ember.Route.extend({
    model: function() {
        return App.Account.find();
    } 
});

// Controllers

App.TransactionsController = Ember.ArrayController.extend();

// Adapter
App.Adapter = DS.RESTAdapter.extend({
    url: 'http://api.mydomain.ca'
});

// Models

App.Store = DS.Store.extend({
  revision: 11,
  adapter: App.Adapter.create({})
});

App.User = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    account: DS.belongsTo('App.Account')
});

App.Account = DS.Model.extend({
    user: DS.belongsTo('App.User'),
    transactions: DS.hasMany('App.Transaction'),
    balance: function() {
      return this.get('transactions').getEach('amount').reduce(function(accum, item) {
          return accum + item;
      }, 0);
  }.property('transactions.@each.amount')
});

App.Transaction = DS.Model.extend({
    account: DS.belongsTo('App.Account'),
    amount: DS.attr('number'),
    description: DS.attr('string'),
    timestamp: DS.attr('date')
});

和车把模板

<script type="text/x-handlebars" data-template-name="application">
    <div class="row">
        <div class="twelve columns">
            <h2>Accounts</h2>
            <p>{{outlet}}</p>
        </div>
    </div>
</script>

<script type="text/x-handlebars" data-template-name="users">
    <div class="row">
        <div class="three columns" id="users">
            {{#each user in controller }}
                {{#linkTo "user" user class="panel twelve columns"}}{{user.firstName}} {{user.lastName}}{{/linkTo}}
            {{/each}}
        </div>
        <div class="nine columns" id="user">
            {{ outlet }}
        </div>
    </div>  
</script>

<script type="text/x-handlebars" data-template-name="user">
    <h2>{{firstName}} {{lastName}}</h2>
    {{#if account}}
    {{render "account" account}}
    {{else}}
    Error: Account not set up!
    {{/if}}
</script>

<script type="text/x-handlebars" data-template-name="accounts">
    <div class="row">
        <div class="three columns" id="accounts">
            {{#each account in controller }}
                {{#linkTo "account" account class="panel twelve columns"}}{{account.id}} {{account.user.firstName}} {{account.user.lastName}}{{/linkTo}}
            {{/each}}
        </div>
        <div class="nine columns" id="account">
            {{ outlet }}
        </div>
    </div>  
</script>

<script type="text/x-handlebars" data-template-name="account">
    <p>Account Number: {{id}}, Balance: {{balance}}, {{transactions.length}} transactions</p>
    {{render "transactions" transactions}}
</script>

<script type="text/x-handlebars" data-template-name="transactions">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Amount</th>
                <th>Timestamp</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
        {{#each transaction in controller}}
            <tr>
                <td>{{transaction.id}}</td>
                <td>{{transaction.amount}}</td>
                <td>{{transaction.timestamp}}</td>
                <td>{{transaction.description}}</td>
            </tr>
        {{/each}}
        </tbody>
    </table>
</script>
于 2013-01-30T21:27:25.443 回答
0

创建一个 Index 路由,为您的 IndexController 提供一个模型,并创建一个相关的模板来迭代您的关系。

这是帖子和评论之间的简单 HasMany-Relationship 示例:

var App = Ember.Application.create();
App.Store = DS.Store.extend({
  revision: 11,
  adapter: DS.RESTAdapter.create()
});

App.Post = DS.Model.extend({
  comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
  post: DS.belongsTo('App.Post'),
  body: DS.attr('string'),
});

App.IndexRoute = Ember.Route.extend({
  setupController: function(controller) {
    controller.set('content', App.Post.find("1"));
  }
});

HTML 代码应如下所示:

<!DOCTYPE html>
<html>
<head>
  ...
</head>
<body>
  <script type="text/x-handlebars" data-template-name="index">
  {{#each comment in content.comments}}
    {{comment.body}}
  {{/each}}
  </script>
</body>

最后但并非最不重要的服务器响应 /posts/1

{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [1, 2, 3]
},

"comments": [{
"id": 1,
"body": "But is it _lightweight_ omakase?"
},
{
"id": 2,
"body": "I for one welcome our new omakase overlords"
},
{
"id": 3,
"body": "Put me on the fast track to a delicious dinner"
}]
}
于 2013-01-29T09:58:21.157 回答