我不明白“可选:正确”如何在轨道上工作?

问题描述

我无法理解optional: true的工作方式。解决了必须存在的错误

error_massage

我正在通过导轨安装以下功能,由于验证,记录未保存。 我听说optional: true允许保存nil记录,但是没有optional: true记录却没有nil的情况下就无法保存。当我尝试访问relation#create时发生错误。

我的代码在这里↓

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable,:lockable,:timeoutable,:trackable and :omniauthable
  devise :database_authenticatable,:registerable,:recoverable,:rememberable,:validatable
         
  has_many :articles
  has_many :goods
  
  has_many :active_relations,class_name: "Relation",foreign_key: :following_id
  has_many :passive_rerations,foreign_key: :follower_id
  
  has_many :followings,through: :active_relations,source: :follower
  has_many :followers,through: :passive_rerations,source: :following
end
class Relation < ApplicationRecord
  belongs_to :followings,class_name: "User",optional: true
  belongs_to :followers,optional: true
end
class RelationsController < ApplicationController
  def create
    follow = current_user.active_relations.new(follower_id: params[:user_id])
    follow.save!
    redirect_to root_path
  end
end
Rails.application.routes.draw do
  devise_for :user
  # For details on the DSL available within this file,see http://guides.rubyonrails.org/routing.html
  root "articles#index"
  resources :articles,except: [:edit,:delete] do
    resources :goods,only: [:create,:destroy]
    get "gooder",on: :member
  end
  resources :users,only: :show do
    resources :relations,:destroy]
    get "followings",on: :member
    get "followers",on: :member
  end
end

解决方法

如果将:optional选项设置为true,则不会验证关联对象的存在。默认情况下,此选项设置为false。否则它将是必需的关联对象。

这将为您提供更多帮助。 read full description

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...