Rails PUT与嵌套模型

时间:2017-11-09 06:31:59

标签: ruby-on-rails active-model-serializers

我的Rails 5.1 API应用中有PostComment个模型

发表

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;
}

1 个答案:

答案 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

提供了很好的文档