Search code examples
ember.jsember-dataember-router

store.find() with relationship-object as parameter?


I've got two models Post.js and Category.js

Post.js

import DS from 'ember-data';

var Post = DS.Model.extend({
  title: DS.attr('string'),
  permalink: DS.attr('string'),
  body: DS.attr('string'),
  category: DS.belongsTo('category')
});

export default Post;

Category.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  permalink: DS.attr('string'),
  posts: DS.hasMany('post',{async:true})
});

I'd like to retrieve all posts belonging to a category via http://localhost:4200/<category_permalink>.

I have trouble to retrieve the data in the route since this doesn't work because of the category.permalink.

Route

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('post', { category.permalink: params.category });
  }
});

Solution

  • First of all, { category.permalink: params.category } is not a valid JSON. What you probably want to achieve is to have such an endpoint:

    GET http://localhost:4200/api/post?category_permalink=:category_permalink`
    

    Then, in Ember, you would rather use:

    this.store.find('post', {
      category_permalink: params.category
    });
    

    and the response from the server should look more or less like that:

    {
      "post": [{
        "id": 1,
        "title": "title",
        "body": "body",
        "permalink": "permalink",
        "category": 10
      }],
      "category": {
        "id": 10,
        "name": "name",
        "permalink": "c_permalink",
        "posts": [1,2,3]
      }
    }