【发布时间】:2020-08-29 09:21:24
【问题描述】:
我不明白如何工作optional: true。它已经解决了必须存在的错误
我正在通过rails安装以下功能,但由于验证,记录没有保存。
我听说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, class_name: "Relation", 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, class_name: "User", 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, only: [:create, :destroy]
get "followings", on: :member
get "followers", on: :member
end
end
【问题讨论】:
-
如果您将
:optional选项设置为true,则不会验证关联对象的存在。默认情况下,此选项设置为false。否则将需要关联对象。这将为您提供更多帮助。 guides.rubyonrails.org/association_basics.html#optional
标签: ruby-on-rails ruby ruby-on-rails-5