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

cho*_*s24 3 ruby ruby-on-rails ruby-on-rails-5

我不明白如何工作optional: true。它已经解决了必须存在的错误

\n

错误按摩

\n

我\xe2\x80\x99m通过rails安装了以下功能,由于验证,记录没有保存。\n我听说optional: true允许保存nil记录,但没有optional: true记录就没有保存'不过没有。当我尝试访问时发生错误relation#create。

\n

我的代码在这里 \xe2\x86\x93

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

小智 6

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

这会对你有更多帮助。阅读完整说明