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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With