如何在rails json中的两个表中插入多个记录并保存数据

时间:2018-05-20 10:05:04

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

你好soem body可以帮我一个例子在rails中做一个post请求来保存json中的diferents表中的多个记录和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

0 个答案:

没有答案