【发布时间】:2020-02-12 06:43:42
【问题描述】:
我的应用有 Rails API 后端和 React 前端。
ERD 只有三个参数:用户has_many :sites、站点belongs_to :user 和has_many :pages,以及页面belongs_to :site。
所有 CRUD 功能都有效,除非我尝试将属于某个站点的页面发布到我的 Active Records 后端。
如果我查看 Rails 控制台,我可以看到它所属的站点和用户:
#<Site:0x00007fbc9ad9fe28 id: 94, name: "Daffy", category: "test", user_id: 1, created_at: Tue, 15 Oct 2019 13:53:23 UTC +00:00, updated_at: Tue, 15 Oct 2019 13:53:23 UTC +00:00>]
但是,当我尝试将页面发布到站点时,站点 ID 会返回 nil
#<Page:0x00007fbc9b5069c8 id: 2, content: "\"\"", site_id: nil, created_at: Tue, 15 Oct 2019 10:51:42 UTC +00:00, updated_at: Tue, 15 Oct 2019 10:51:42 UTC +00:00>]
查看 Chrome 开发工具,我收到错误 422:
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)
:3000/users/1/sites/94/pages/:1
&在预览选项卡下的网络中,我得到
{site: ["must exist"]}
site: ["must exist"]
我查看了以下与此相关的 StackOverflow 帖子:
POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller?
和
Validation failed Class must exist
但在我的特定情况下都不起作用。
站点控制器.rb
class SitesController < ApplicationController
before_action :set_site, only: [:show, :update, :destroy]
before_action :authorize_request, only: [:create]
...
def create
@site = Site.new(site_params)
@current_user.sites << @site
render json: @site, status: :created
end
...
def site_params
params.require(:site).permit(:name, :category, :user_id)
end
end
我已经研究了一段时间,我希望比我更了解 Rails 的人能指出我所缺少的。
【问题讨论】:
-
我可能不完全理解发生了什么,但您不想要 Site.create 而不是 Site.new 吗? Site.new 在保存之前不会创建 id。
标签: ruby-on-rails