Reputation: 46
In ember.js/ember-data.js, is there a way to have the store POST to rails such that it sends information to create a model and its associations? Let me provide some context.
Suppose I have 3 rails models:
class Post < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
attr_accessible :categories_attributes
accepts_nested_attributes_for :categories
end
class Categories < ActiveRecord::Base
has_many :categorizations
has_many :posts, :through => :categorizations
end
class Categorizations < ActiveRecord::Base
belongs_to :post
belongs_to :categories
end
In ember.js, I want to be able to create a post along with its categorizations in one request. This is what I have done to achieve that:
App.Category = DS.Model.extend
name: DS.attr 'string'
App.Categorization = DS.Model.extend
post: DS.belongsTo 'App.Post'
category: DS.belongsTo 'App.Category'
App.Post = DS.Model.extend
title: DS.attr 'string'
content: DS.attr 'string'
categorizations: DS.hasMany 'App.Categorization',
embedded: true
toJSON: (options={}) ->
options.associations = true
@_super(options)
# meanwhile, somewhere else in code...
post = App.store.createRecord App.Post,
title: "some title"
content: "blah blah"
transaction = App.store.transaction()
categorization = transaction.createRecord App.Categorization,
category: category # an instance of DS.Category
post.get('categorizations').pushObject categorization
# XXX: This enables ember-data to include categorizations in the post hash when
# POSTing to the server so that we can create a post and its categorizations in
# one request. This hack is required because the categorization hasn't been
# created yet so there is no id associated with it.
App.store.clientIdToId[categorization.get('clientId')] = categorization.toJSON()
transaction.remove(categorization)
App.store.commit()
I'm trying to make it so that when App.store.commit() is called it POSTs to /posts with something like:
{
:post => {
:title => "some title",
:content => "blah blah,
:categorizations => [ # or :categorizations_attributes would be nice
{
:category_id => 1
}
]
}
}
Is there a way to achieve this without having ember POST to categorizations_controller to create the categorizations?
Upvotes: 2
Views: 558
Reputation: 5056
You should take a look at what the RESTAdapter
does with its bulkCommit
option. The RESTAdapter
is intended to work with Rails but you'll probably need to do a little bit of config on the Rails side to fully support it. See https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js
Upvotes: 1