Emberjs + Rails - TypeError:无法调用未定义的方法'hasOwnProperty'(无法POST到Rails DB)

Bry*_*ong 5 ember.js ember-data ember-rails

我试图用Emberjs和ember-data将一条新记录发布到Rails db中; 但是我收到以下错误:

TypeError {}"无法调用方法'hasOwnProperty'未定义"

我一直在关注https://github.com/dgeb/ember_data_example的示例,并尝试使用与示例相同的概念构建我自己的应用程序.更何况,我使用过调试器; 在我的控制器中,当我在控制台中点击this.get('preLoadedData')时,它设法将我的输入提取到表单中.但是,问题是我无法将用户输入POST到Rails DB中.

代码是:

商店

DS.RESTAdapter.configure("plurals", {"company_category": "company_categories"});
  App.Adapter = DS.RESTAdapter.extend({
    bulkCommit: false
});

App.Store = DS.Store.extend({
  revision: 12,
  adapter: DS.RESTAdapter.create()
});
Run Code Online (Sandbox Code Playgroud)

模型

App.CompanyCategory = DS.Model.extend({
    category:   DS.attr("string")
});
Run Code Online (Sandbox Code Playgroud)

调节器

App.CompanyCategoriesNewController = Em.ObjectController.extend({

    startEditing: function() {
        this.transaction = this.get('store').transaction();
        this.set('model', this.transaction.createRecord(App.CompanyCategory, {}));
    },

    save: function() {
        this.transaction.commit();
        this.transaction = null;
    }
});
Run Code Online (Sandbox Code Playgroud)

在rails控制器下: -

def create
    @category = CompanyCategory.new(params[:id])
    respond_to do |format|
      if @category.save
        format.json { render json: @category, status: :created, location: @category }
      else
        format.json { render json: @category.errors, status: :unprocessable_entity}
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

路由器

App.CompanyCategoriesNewRoute = Em.Route.extend({
   model: function() {
       return null;
   },

   setupController: function(controller) {
       this._super.apply(this,arguments);
       controller.startEditing();
   }
});
Run Code Online (Sandbox Code Playgroud)

当我调用App.CompanyCategory.find()时,我的JSON输出; 是:

{
   "company_categories":[
           {"id":1,"category":"Financial Services"},
           {"id":2,"category":"Trade Services"}
   ]
}
Run Code Online (Sandbox Code Playgroud)

我可以知道我做错了什么吗?提前致谢!

Hri*_*shi 0

这里有几件事,让控制器设置自己的模型被认为是不好的做法。相反,路由器的工作是向控制器提供模型。所以根据 ember 的做事方式,你应该这样做:

App.CompanyCategoriesNewRoute = Em.Route.extend({
   model: function() {
    return this.get('store').createRecord(App.CompanyCategory, {});
   },

  setupController: function(controller, model) {
    controller.set('content', model);
  }
});

App.CompanyCategoriesNewController = Em.ObjectController.extend({


    startEditing: function() {
       this.set('transaction', this.get('store').transaction());
       this.get('transaction').add(this.get('model'));
   },

   save: function() {
     this.get('transaction').commit();
  }
Run Code Online (Sandbox Code Playgroud)

});