【问题标题】:Rails PUT with nested model带有嵌套模型的 Rails PUT
【发布时间】:2017-11-09 06:31:58
【问题描述】:

我在我的 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;
}

【问题讨论】:

  • 显示您的帖子表单
  • /post/:id中的表格是供用户输入cmets的。我已经从 Angular 2 客户端添加了 PostComment 模型 - 希望这涵盖了它。

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


【解决方案1】:

您可以使用 Post 模型中的 accepts_nested_attributes_for cmets。如果将 cmets 属性作为没有 id 参数的嵌套属性传递,则会创建新记录。如果你用现有的 id 传递它,现有的记录将相应地更新。

class Post < ApplicationRecord
  has_many :comments

  accepts_nested_attributes_for :comments
end

并且帖子参数应该允许嵌套属性

def post_params
  params.require(:post).permit(:id, :title, ... , 
    comments_attributes: [:id, :comment] # Provide comment model attributes here]
  )
end

Rails 对此有很好的文档here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多