【发布时间】:2017-11-09 06:31:58
【问题描述】:
我在我的 Rails 5.1 API 应用程序中有 Post 和 Comment 模型,如下所示
发帖
class Post < ApplicationRecord
has_many :comments
end
评论
class Comment < ApplicationRecord
belongs_to :post
end
**Post Serializer(使用 ActiveModel Seriazlier)**
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :text, :created_at
has_many :comments
end
当用户访问 /posts/:id 并通过前端应用程序 (Angular 2) 向帖子添加评论时,我将调用 PUT /posts:id,其中 post 对象嵌套在现有的 comments 和新评论。
如何在post_controller.rb 中处理这个问题,以便将新的comment 插入到具有正确菜肴关联的数据库中?
我的post#update方法如下
# PATCH/PUT /post/1
def update
if @post.update(post_params)
render json: @post
else
render json: @post.errors, status: :unprocessable_entity
end
end
更新:
我正在从我的 Angular 2 客户端添加 Post 模型。 Post 模型有 Comment[] 作为成员之一。当通过表单添加新评论时,comment 被推送到 post.comments 数组,然后将整个对象发送到 Rails API 后端。
Post 客户端模型
import { Comment } from './comment';
export class Post {
id: number;
title: string;
text: string;
date: string;
comments: Comment[];
}
Comment 客户端模型
export class Comment {
comment: string;
date: string;
}
【问题讨论】:
-
显示您的帖子表单
-
/post/:id中的表格是供用户输入cmets的。我已经从 Angular 2 客户端添加了Post和Comment模型 - 希望这涵盖了它。
标签: ruby-on-rails active-model-serializers