ruby-on-rails - 如何在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
解决方案
您到底想用 Post 和 Comment 做什么?您可以为 Post / PostController 设置表单,然后接受评论的嵌套属性吗?
也许看看 Simple Form 的嵌套模型。 https://github.com/plataformatec/simple_form/wiki/Nested-Models
此外,发布您的评论/帖子模型及其关联也会有所帮助。
推荐阅读
- tfs - 从 Azure Data Studio 连接到 Team Foundation Server
- c - 我的代码不工作。我做错了吗?
- angular6 - 刷新如何在angular6中保持相同的路线?
- php - 如何使用 PHP 的 PDO 对象发送 SQL 更新查询
- debian - 安装 rsyslog(Debian)时出现问题。存储库未签名
- python - 如何使用 FOR 循环将两个列表中的元素附加到一个空列表中?
- android - 检测设备是否关闭了 touch id 功能
- java - 如何修复我的 do-while 循环中的逻辑,然后应用 try-catch 块来捕获并显示来自另一个类的错误消息?
- ios - 点击 SWIFT 获取 NSAttributed 字符串颜色
- typescript - 如何使用泛型的类名作为结果类型的字符串值