简体   繁体   中英

I don't understand how “optional: true” work on rails?

I can't understand how to work optional: true . It has solved the must exist error

错误按摩

I'm installing the following function by rails, and the record didn't save because of validation. I've heard that optional: true permit saving nil record, but it didn't save without optional: true record didn't have nil though. The error occurred when I tried to access relation#create .

My code is here ↓

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

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false . otherwise it will be required associated object.

this will help you more. read full description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM