【问题标题】:how can I insert multiples record and save data in two tables in rails json如何在rails json的两个表中插入多个记录并将数据保存
【发布时间】:2018-05-20 10:05:03
【问题描述】:

你好 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

【问题讨论】:

  • 您可以添加您当前的代码来保存单个记录吗?
  • Just add 正在等待添加另一个表,但我不知道如何将数据保存在两个不同的表中并保存多个数据
  • 你到底想用帖子和评论做什么?您可以为 Post / Post Controller 设置表单,然后接受 cmets 的嵌套属性吗?

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2016-11-05
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多