我正在使用 Can.js 向 Ruby on Rails 服务器添加记录:
var Todo = can.Model({
findAll : 'GET /todos',
findOne : 'GET /todos/{id}',
create : 'POST /todos',
update : 'PUT /todos/{id}',
destroy : 'DELETE /todos/{id}'
}, {});
Todo.prototype.description = function() {
return this.name + " and " + this.complete;
};
Todo.findAll({}, function(todos) {
todos.each(function(todo) {
console.log(todo.name, todo.complete);
console.log(todo.description());
});
});
var todo = new Todo({name: "mow lawn"});
todo.save();
实际上可以获取所有记录,findAll()
但是save()
会插入一条空白记录。我怀疑它可能是CSRF token
,但这显示为警告,如果它不想插入记录,它可能根本不会创建任何记录,而不是添加名称为空的记录?(我也试过var todo = new Todo({name: "mow lawn", complete: true});
了,结果是一样的)。
但 Rails 服务器在终端上打印为:
Started POST "/todos" for 127.0.0.1 at 2013-04-12 08:16:05 -0700
Processing by TodosController#create as JSON
Parameters: {"name"=>"mow lawn"}
WARNING: Can't verify CSRF token authenticity
(0.2ms) begin transaction
SQL (0.8ms) INSERT INTO "todos" ("complete", "created_at", "name", "updated_at")
VALUES (?, ?, ?, ?) [["complete", nil], ["created_at", Fri, 12 Apr 2013 15:16:05 UTC
+00:00], ["name", nil], ["updated_at", Fri, 12 Apr 2013 15:16:05 UTC +00:00]]
(1.5ms) commit transaction
Completed 201 Created in 11ms (Views: 1.3ms | ActiveRecord: 2.5ms)
在 Chrome 开发者工具中,我在 Network 中看到:
Request URL:http://localhost:3000/todos
Request Method:POST
part of header:
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
form data:
name:mow lawn
如果我的操作是:
def create
p "params[:todo] is", params[:todo]
@todo = Todo.new(params[:todo])
respond_to do |format|
if @todo.save
format.html { redirect_to @todo, notice: 'Todo was successfully created.' }
format.json { render json: @todo, status: :created, location: @todo }
else
format.html { render action: "new" }
format.json { render json: @todo.errors, status: :unprocessable_entity }
end
end
end
然后终端将显示:
"params[:todo] is"
nil
即使终端显示标准 Rails 日志:
Parameters: {"name"=>"mow lawn"}