6

RESTfulサーバー上のこれらのJSONデータモデルを考えると

/ users

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

/ users / 1

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

/アカウント

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

/ accounts / 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')
});

データをモデルにロードしてから、ユーザーの名前、アカウントID、およびアカウント内のトランザクション数を出力するテンプレートを作成するには、他にどのような残り火コードを作成する必要がありますか?

4

2 に答える 2

3

私はこれを解決することができたので、他の誰かに役立つ場合に備えてコードを投稿します。秘訣は、JSONデータがEmberが望むとおりに正確にフォーマットされていることを確認し、適切なルートを作成することです。

私の知る限り、Emberは親オブジェクトが子オブジェクトのリストを提供することを期待しています。これは私には奇妙に感じるので、外部キーを使用して親を参照する子オブジェクトを使用してそれを行う方法を誰かが知っている場合は、私に知らせてください。

/ user /:user_id JSONオブジェクトのaccountプロパティをaccount_idに変更しました。また、/ usersにあるuserオブジェクトのaccount_idも含め、アカウントのowned_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

IndexControllerにモデルをシードするインデックスルートを作成し、関係を反復する関連テンプレートを作成します。

簡単なHasManyの例を次に示します-投稿とコメントの関係:

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 に答える