在ember.js/ember-data.js中,有没有办法让store POST到rails,这样它就可以发送信息来创建模型及其关联?让我提供一些背景信息。
假设我有3个rails模型:
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在ember.js中,我希望能够在一个请求中创建一个帖子及其分类。以下是我为实现这一目标所做的工作:
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()我正在尝试这样做,这样当调用App.store.commit()时,它会使用如下内容发送到/posts:
{
:post => {
:title => "some title",
:content => "blah blah,
:categorizations => [ # or :categorizations_attributes would be nice
{
:category_id => 1
}
]
}
}有没有一种方法可以做到这一点,而不是让ember POST到categorizations_controller来创建分类?
发布于 2012-10-12 08:34:50
您应该看看RESTAdapter对它的bulkCommit选项做了什么。RESTAdapter旨在与Rails一起工作,但您可能需要在Rails端进行一些配置才能完全支持它。请参阅https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js
https://stackoverflow.com/questions/12850495
复制相似问题