如何在 rails json 的两个表中插入多个记录并保存数据
how can I insert multiples record and save data in two tables in rails json
你好 soem body 可以用 rails 中的一个示例帮助我执行 post 请求以在 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
您究竟想用 Post 和评论做什么?
您可以为 Post / PostController 设置表单,然后接受 Comments 的嵌套属性吗?
或许可以查看 Simple Form 的嵌套模型。
https://github.com/plataformatec/simple_form/wiki/Nested-Models
此外,发表您的评论/Post 模型及其关联会有所帮助。
你好 soem body 可以用 rails 中的一个示例帮助我执行 post 请求以在 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
您究竟想用 Post 和评论做什么? 您可以为 Post / PostController 设置表单,然后接受 Comments 的嵌套属性吗?
或许可以查看 Simple Form 的嵌套模型。 https://github.com/plataformatec/simple_form/wiki/Nested-Models
此外,发表您的评论/Post 模型及其关联会有所帮助。