我在我的项目中添加了这个 gem 用于 json 序列化:gem 'jsonapi-serializer'
在发布请求时,我在创建时收到以下错误:
FastJsonapi::MandatoryField (id is a mandatory field in the jsonapi spec)
我的模型很简单:
class Post < ApplicationRecord
belongs_to :profile
belongs_to :category
validates :title, presence: true
validates :content, presence: true
validates :category_id, presence: true
validates :profile_id, presence: true
end
后控制器中此方法的保存部分是出现问题的地方:
def create
@post = Post.new(post_params)
if @post.save
render json: PostSerializer.new(@post).serializable_hash.as_json, status: :created
else
render json: PostSerializer.new(@post.errors).serializable_hash.as_json, status: :unprocessable_entity
end
end
在我的帖子请求中,我使用JSON.Stringify()
了哪个控制台日志打印:{"title":"Hello","content":"Hello World","category_id":"1","profile_id":"1"}
Rails 打印的参数:
Parameters: {"title"=>"Hello", "content"=>"Hello World", "category_id"=>"1", "profile_id"=>"1", "post"=>{"title"=>"Hello", "content"=>"Hello World", "category_id"=>"1", "profile_id"=>1}}
我之前尝试的格式是将数据包装在 Post 对象中,这是同样的错误。
我试图模拟 id 但我仍然收到错误。我还尝试删除序列化程序,但我得到了一个简单的无法处理的实体错误。不过,通过控制台直接创建帖子是可行的。
在另一个项目上测试,我没有收到任何错误,所以它可能不是序列化程序的错。但是,我不确定在这种情况下还能去哪里看。提前致谢!
编辑:要求的 PostSerializer 代码
class PostSerializer
include FastJsonapi::ObjectSerializer
belongs_to :profile
attributes :id, :category_id, :title, :content
end