Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "find or create" with Ember Data

Currently I'm hitting a wall with Ember Data loading some data which might exist or might not. If a record does not exist, the web application should create it.

Simple use case: documenting an inventory. If an article does not exist, a new article should be added. If it does exist, then the employee can immediately use the information.

I suspect the adapter find() method to be the source of this problem. It cannot handle a 404 not found error and passing an empty result does not work either.

Probably I am overlooking something trivial, as 'find or create' is quite a regular pattern. Please help...

like image 585
user1998398 Avatar asked Feb 12 '13 14:02

user1998398


2 Answers

See this issue, or here's the solution:

findOrCreate: (type, properties)->
  @store.find(type, properties.id).then null, (reason)=>
    if reason.status == 404
      record = @store.recordForId(type, properties.id)
      record.loadedData()
      record.setProperties(properties)
      record.save()
    else
      throw reason
like image 144
simon Avatar answered Oct 16 '22 07:10

simon


see #296 Already a bug report for this

like image 1
pjlammertyn Avatar answered Oct 16 '22 06:10

pjlammertyn