Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create has_and_belongs_to_many relationship with Ember.js & ember-data?

Is it possible to create a hasAndBelongsToMany relationship with Ember.js & ember-data?

Edit: Added ActiveRecord model examples to clarify.

class Project < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :projects
end

I have an associative table "projects_tags" linking project_id <=> tag_id.

like image 373
David Avatar asked Aug 20 '12 17:08

David


1 Answers

In this example, I'd suggest embedding the tags in the Post, so that the resulting structure looks like this

{
   title: "some post",
   tags: [ "tag1", "tag2" ]
}

This is generally good practice when you don't need to have additional value on the relation. If you want to have the Tag model on the client, you can still do it via embedding.

{
   title: "some post",
   tags: [ { name: "first tag" }, { name: "second tag" } ]
}

in this case you could specify it as an embedded relation, such as this

App.Post = DS.Model.extend({
  title: DS.attr("string"),
  tags: DS.hasMany("App.Tag")
});

App.Tag = DS.Model.extend({
  name: DS.attr("string"),
  post: DS.belongsTo("App.Post")
});

App.store.adapter.serializer.map("App.Tag", {
  tags: { embedded: 'load' }
});

keep in mind that embedding only works in Ember Data revision 10. It is not supported in 5-9.

Most of the time you don't really want to model everything the same way as you would model it in a relation database.

You should lean towards NoSQL-ish JSON, which generally means embedding things, rather than making complex associations. The reason for this is that your database can JOIN data very efficiently, especially with indexes, but doing this over the network is a bad idea because it results in a lot of requests.

like image 52
Jakub Arnold Avatar answered Oct 25 '22 19:10

Jakub Arnold