【发布时间】:2012-10-12 00:13:39
【问题描述】:
在 ember.js/ember-data.js 中,有没有办法让 store 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
}
]
}
}
有没有办法实现这一点,而无需将 ember POST 发送到 categorizations_controller 来创建分类?
【问题讨论】:
-
我觉得这和我一直trying to accomplish做的事情非常相似,但仍然没有成功。
-
@derrick 请在您解决此问题后回复您的解决方案。