在ember.js / ember-data.js中,有没有办法让商店POST到rails,以便它发送信息来创建模型及其关联?让我提供一些背景信息。
假设我有3个导轨型号:
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
}
]
}
}
有没有一种方法可以实现这一点,而无需使用POST给Categorizations_controller来创建分类?
答案 0 :(得分:1)
您应该查看RESTAdapter
对bulkCommit
选项的作用。 RESTAdapter
旨在与Rails一起使用,但您可能需要在Rails端进行一些配置才能完全支持它。见https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js