2

在 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
      } 
    ]
  }
}

有没有办法在没有 ember POST 到 categorizations_controller 来创建分类的情况下实现这一点?

4

1 回答 1

1

你应该看看RESTAdapter它的bulkCommit选项做了什么。旨在与 Rails 一起使用RESTAdapter,但您可能需要在 Rails 端进行一些配置以完全支持它。请参阅https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js

于 2012-10-12T00:34:50.010 回答