我正在尝试使用 Ember on Rails 设置应用程序的基础知识,但出现此错误:
处理路线时出错:帖子
如果 Ember 对错误说了什么会很有帮助,但事实并非如此。这是有问题的代码(我相信我包括了所有需要的部分)。
// PostsRoute
App.PostsRoute = Ember.Route.extend({
model: function(){
return this.store.find('post');
// return [{title: 'fixture'}, {title: '2'}]
}
})
// Router.
App.Router.map(function() {
// location: 'auto',
// rootURL: '/',
this.resource('posts', { path: '/' })
});
// Routes.rb
resources :posts do
resources :comments
end
// Post model - Ember
App.Post = DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
imageFileName: DS.attr('string'),
imageContentType: DS.attr('string'),
imageFileSize: DS.attr('number'),
imageUpdatedAt: DS.attr('date'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date'),
userId: DS.attr('number'),
});
// Posts controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@posts = Post.all
puts "in PostsController index. "
puts @posts
respond_with(@posts)
end
...
// Post Serializer
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :description, :created_at, :updated_at, :user_id, :image_file_name, :image_content_type, :image_file_size, :image_updated_at
end
我试图了解 Ember 需要设置什么才能从 Rails API 接收数据。Rails 方面,它返回数据很好。
据我了解,这就是应用程序的运行方式。Ember 首先检查路线(此处为 PostsRoute)。该路线预计有一个“模型”,因此它会查看模型属性。在这里,模型属性调用 Store 以获取所有帖子。即this.store.find('post')。[用静态数组替换这个调用似乎工作正常。]
这会调用 Rails PostsController 的 index 函数。由于我放在那里的打印语句,我可以确认已达到此功能。index 函数返回一个带有 activerecord 帖子模型的变量。
从这里开始,帖子需要进行 JSON 化,以便 Ember 能够使用它。所以它们通过一个序列化程序,这里是 post_serializer.rb。这决定了以 JSON 形式发送的属性。
我怀疑我处理此序列化部分的方式存在一些问题,因为我已确认帖子实际上已在 PostsController.rb 的索引函数中获取,但未能(我相信)返回余烬。
我不明白为什么。我错过了什么?
如果这是任何问题,我还没有包括一些 has_many 关系,因为我首先想实现这一点。为了完整起见,这里是根据 chrome 控制台的完整错误:
Error while processing route: posts ember.js?body=1:15376
logToConsole ember.js?body=1:15376
logError ember.js?body=1:26315
defaultActionHandlers.error ember.js?body=1:26272
triggerEvent ember.js?body=1:26363
trigger ember.js?body=1:46876
Transition.trigger ember.js?body=1:46721
(anonymous function) ember.js?body=1:46526
tryCatch ember.js?body=1:47310
invokeCallback ember.js?body=1:47322
publish ember.js?body=1:47293
publishRejection ember.js?body=1:47235
(anonymous function) ember.js?body=1:29438
DeferredActionQueues.invoke ember.js?body=1:682
DeferredActionQueues.flush ember.js?body=1:752
Backburner.end ember.js?body=1:138
Backburner.run ember.js?body=1:193
run ember.js?body=1:18226
hash.error ember-data.js?body=1:1886
fire jquery.js?body=1:3120
self.fireWith jquery.js?body=1:3232
done jquery.js?body=1:9278
callback jquery.js?body=1:9686