Nullable relationship doesn't return null


#1

Hi, I want to know if is possible to set a relationship to null, something like this:

import DS from 'ember-data';

var book = DS.Model.extend(
    {
	name: DS.attr('string'),
	author: DS.belongsTo('author', {async: false})
    }
);

export default book;

And this is what is returned by the api:

{
"data": [
	    {
		    "id": 1,
		    "name": "Awesome Ember book",
	  	    "author_id": null
    	    }
	]
}

But when I try to do this:

 let author = book.get ("author");

I’m getting this error:

Uncaught Error: Assertion Failed: You looked up the 'author' relationship on a 'book' with id 1 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)

I was expecting to get a null value, but instead of this, I get that error. If I use async: true, ember will make a request to

GET /books

And I’ll get this error:

TypeError: Cannot read property 'getRecord' of undefined

So, is this a bug? Or I’m missing something


#2

I believe what you need to do is pass back an empty array instead of null. Rather than change the server code, though,you could make the adjustment in a Serializer. Or, simply check for a null author_id in your code before trying to fetch the author. But the Serilaizer would be a more robust solution.