1

Postは多くCommentの s を持つモデルを持っています。の応答GET /posts/12は、かなり Ember-Data に適しています。

{
  "post": {
    "id": 12,
    "title": "I Love Ramen",
    "created_at": "2011-08-19T14:22",
    "updated_at": "2011-08-19T14:22",
    "body": "..."
  }
}

ただし、そのPostの のAPIは であり、これは次を返しますCommentGET /posts/12/comments

{
  "comments": [
    {
      "id": 673,
      "author_id": 48,
      "created_at": "2011-08-21T18:03",
      "body": "Me too!"
    }
  ]
}

Post 12モデルまたはアダプタに対して、のCommentに を使用することを伝えるにはどうすればよい/posts/12/commentsですか? Post自体はCommentIDを認識していないことに注意してください。

アップデート

buuda の回答に応じて、いくつかの説明があります。

は、(a)のコメントを表示し、(b) のようなプロパティを持つことができるように、Postその を検索できる必要があります。CommentPostRoutePost

hasComments: function() {
  return this.get('comments.length') > 0;
}.property('comments')

commentsただし、計算されたプロパティを実装する必要がある場合は問題ありません。上記の回答で、ブダは示唆しています

App.Comments.find({ id: postId });

/posts/:postId/commentsの代わりにデータストアを取得するにはどうすればよい/comments?postId=:postIdですか?

4

1 に答える 1

2

必ずしもモデル間の関係をセットアップする必要はありません。ネストされたリソースにより、適切なデータを取得できます。このルーターでは:

App.Router.map(function() {
  this.resource('posts', { path: '/posts/:post_id' }, function() {
    this.route('edit');
    this.resource('comments', function() {
      this.route('new');
    });
  });
});

CommentsRou​​te は、それが含まれているリソースのモデルを取得し、その投稿 ID を持つコメントを取得できます。

App.CommentsRoute = Ember.Route.extend({
   model: function() {
       var post = this.modelFor('posts');
       var postId = post.get('id');
       return App.Comments.find({ id: postId });
   }
});

投稿モデルはコメント ID を知る必要はありませんが、基になるデータストアは投稿 ID クエリに基づいて適切なコメントを返す必要があります。返された配列は、コメント ルートのモデルとして使用されます。

編集:

ember-dataを使用していると思います。その場合、ネストされたリソース URL (posts/:postId/comments) はまだサポートされていません。投稿ルートでコメントを表示するには、コメント データを取得してコメント コントローラーに設定し、投稿コントローラーでコントローラー インジェクション (「ニーズ」) を使用し、実験的な「control」ハンドルバー タグを使用してコメント ビューを表示します。 :

App.PostsRoute = Ember.Route.extend({
   setupControllers: function() {
       var post = this.modelFor('posts');
       var postId = post.get('id');
       var comments = App.Comments.find({ id: postId });
       this.controllerFor('comments').set('content', comments);
   }
});

ここで、実験的なコントロール タグの使用方法を説明します: How to Render HasMany Associations With Their Own Controller

于 2013-03-13T03:47:56.203 に答える