【问题标题】:Ember.js Rails: Error while loading route: Error: No model was found for '0'Ember.js Rails:加载路线时出错:错误:找不到'0'的模型
【发布时间】:2014-05-29 06:47:56
【问题描述】:

在尝试将 Ember.js 应用程序连接到 Rails 3.2 API 时,我不断收到“找不到 '0' 的模型”错误。我的设置如下。任何帮助将不胜感激。

项目控制器(Rails)

def index

  @items = Item.all

  respond_to do |format|
    format.html
    format.json { render json: @items, root: true }
  end

end

App.js (Ember.js)

App = Ember.Application.create();

App.Router.map(function() {
  this.resource('items', function() {
    this.route('backlog');
    this.route('board');
  });
});


App.ItemsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('item');
  }
});

Ember 应用向 /items 发出请求时的服务器响应

[
  {
    "item": {"id":1,"item_type":"Item","name":"Test item"}
  },
  { 
    "item": {"id":2,"item_type":"Item","name":"Test item 2"}
  }
]

【问题讨论】:

    标签: ruby-on-rails ember.js


    【解决方案1】:

    假设您使用的是 Ember-Data,您的 JSON 格式不正确。它的记录相当差,所以不要难过。 RESTAdapter 有一个简短的示例,但JSON API 提供了更多详细信息。就您而言,我认为您希望您的回复如下所示:

    {
        "items": [
            { "id": 1, ... },
            { "id": 2, ... }
        ]
    }
    

    【讨论】:

    • 我正在使用 Ember-Data 并且已经看到这种格式是预期的。如何配置 Rails 和/或我的控制器以这种格式响应?
    • 我使用 active_model_serializers gem 让它工作。添加 gem 并为我的项目模型创建序列化程序(使用 rails g 序列化程序项目)后,它会以您描述的 json 格式响应并且它可以工作!
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多