Rails API-React:站点ID在POST上返回null

时间:2019-10-15 14:36:58

标签: ruby-on-rails

我的应用程序具有Rails API后端和React前端。

ERD只有三个参数:用户has_many :sites,站点belongs_to :userhas_many :pages,以及页面belongs_to :site

除了我尝试将属于站点的页面发布到我的Active Record后端之外,所有CRUD功能都起作用。

如果我查看Rails Console,我可以看到站点及其所属的用户:

#<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

但在我的特定情况下都不起作用。

SitesController.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的了解比我知道的要多得多。

1 个答案:

答案 0 :(得分:1)

问题出在您的<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00292525" android:backgroundTint="#00242020" android:orientation="horizontal" android:paddingStart="60dp"> <ImageView android:id="@+id/img_like" android:layout_width="35dp" android:layout_height="45dp" app:srcCompat="@drawable/date" /> <TextView android:id="@+id/lbl_date" android:layout_width="wrap_content" android:layout_height="45dp" android:ems="5" android:text="what is up" android:gravity="center" android:textColor="#062AEE" android:textStyle="bold" /> ... <!-- More ImageViews and TextViews --> ... </LinearLayout> 动作中。正如create指出的那样,zakariah1只会初始化Site.new,您需要使用Site将其保存在数据库中。

此外,您在执行操作时不需要此代码Site.create。由于您的@current_user.sites << @site拥有site_params,因此Rails关联会为您做到这一点。

这就是您的控制器的外观:

user_id