首页 > 解决方案 > 如何在rails json的两个表中插入多个记录并将数据保存

问题描述

你好,soem body 可以帮助我在 Rails 中使用一个示例来执行发布请求,以在 json 中的不同表中保存多个记录和 sabe 数据

{   
  "post":
  {
    "title":"Titlea 2",
    "body":"body of the post 2"
  }
  "comment":[
    {
      "title":"Title 2",
      "body":"body of the post 2"
    },
    {
      "title":"Title 2",
      "body":"body of the post 2"
    }
  ]
}

实际上我有基本的脚手架代码,我在 Rails 中非常新

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :update, :destroy]
  def index
    @comments = Comment.all
    render json: @comments
  end
  def show
    render json: @comment
  end

  # POST /comments
  def create
    @comment = Comment.new(comment_params)

    if @comment.save
      render json: @comment, status: :created, location: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  private
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def comment_params
      params.require(:comment).permit(:title, :comment)
    end
end

标签: ruby-on-railsjsonruby-on-rails-4

解决方案


您到底想用 Post 和 Comment 做什么?您可以为 Post / PostController 设置表单,然后接受评论的嵌套属性吗?

也许看看 Simple Form 的嵌套模型。 https://github.com/plataformatec/simple_form/wiki/Nested-Models

此外,发布您的评论/帖子模型及其关联也会有所帮助。


推荐阅读