问题描述
我无法理解optional: true
的工作方式。解决了必须存在的错误
我正在通过导轨安装以下功能,由于验证,记录未保存。
我听说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