我的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;
}
答案 0 :(得分:1)
您可以使用Post模型中的accepts_nested_attributes_for
条评论。如果将注释属性作为没有id参数的嵌套属性传递,则将创建新记录。如果您使用现有ID传递它,现有记录将相应更新。
class Post < ApplicationRecord
has_many :comments
accepts_nested_attributes_for :comments
end
post params应该允许嵌套属性
def post_params
params.require(:post).permit(:id, :title, ... ,
comments_attributes: [:id, :comment] # Provide comment model attributes here]
)
end
Rails为此here
提供了很好的文档