ruby-on-rails - 为什么我的记录保存后全是零字段?
问题描述
我正在制作一个 ember 和 rails 应用程序。
我正在尝试向http://localhost:3000/candidates发出发布请求
我的请求是获得 200 并且正在创建记录,但一切都是零:这是为什么?
#<Candidate id: 15, name: nil, email: nil, created_at: "2018-08-23 22:28:07", updated_at: "2018-08-23 22:28:07">
这是我的控制器代码:
class CandidatesController < ApplicationController
# POST /candidates
# def create
# @candidate = Candidate.create!(candidate_params)
# json_response(@candidate, :created)
# end
def create
puts "create"
puts params
puts candidate_params
candidate = Candidate.create!(candidate_params)
if candidate.save
render jsonapi: candidate
else
render jsonapi_errors: candidate.errors
end
end
private
def candidate_params
# whitelist params
params.permit(:name, :email)
end
end
这是我的余烬代码:
import Ember from "ember";
export default Ember.Route.extend({
model() {
// return this.get("store").findAll("candidate");
},
actions: {
createCandidate() {
console.log("create candidate");
let candidate = this.get("store").createRecord("candidate", {
id: 1,
name: "Katie",
email: "katie@gmail.com"
});
candidate.save();
}
}
});
我的 js 控制台中也出现此错误:SyntaxError: Unexpected end of JSON input
我正在使用“jsonapi-rails”gem
这是服务器日志和网络选项卡的屏幕截图:
Started POST "/candidates" for 127.0.0.1 at 2018-08-29 14:07:12 +0100
Processing by CandidatesController#create as application/vnd.api+json
create
{"controller"=>"candidates", "action"=>"create"}
{}
(2.7ms) begin transaction
↳ app/controllers/candidates_controller.rb:12
Candidate Create (0.4ms) INSERT INTO "candidates" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2018-08-29 13:07:12.984174"], ["updated_at", "2018-08-29 13:07:12.984174"]]
↳ app/controllers/candidates_controller.rb:12
(1.3ms) commit transaction
↳ app/controllers/candidates_controller.rb:12
(0.1ms) begin transaction
↳ app/controllers/candidates_controller.rb:14
(0.0ms) commit transaction
↳ app/controllers/candidates_controller.rb:14
Completed 200 OK in 9ms (Views: 0.1ms | ActiveRecord: 4.5ms)
这是我的适配器:
import DS from "ember-data";
export default DS.JSONAPIAdapter.extend({
host: "http://localhost:3000",
dataType: "json"
});
我没有在前端使用任何序列化程序。我可以做?是的,我期待 jsonapi 数据。
解决方案
您必须在您的 ember 应用程序中定义一个模型: https ://guides.emberjs.com/release/models/#toc_models
此外,如果你使用的是 jsonapi 规范,你应该设置相关的适配器
// app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({});
// app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({});
推荐阅读
- java - 从 openjdk11 访问 com.sun.* 类
- excel - 用于复制并粘贴到 BS 列的下一个空行的宏
- pybind11 - VS2017 与 pybind11 一起使用时会引发链接器错误
- c# - 等待第三方 API 回调
- c# - UWP C#:从本地磁盘打开 HTML 文件到默认浏览器
- javascript - addEventListener 没有在按键上触发
- php - 如果身体标签通过子主题具有“家”类
- python - 用Python模拟退火算法解决旅行商问题
- python-3.x - 如何使用 Youtube Data API v3 获取 youtube 频道中的所有视频标题?
- google-admin-sdk - 查询 Admin Report API 以了解用户活动时未返回任何项目