繁体   English   中英

我不明白“可选:真实”如何在导轨上工作?

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

我无法理解如何使用optional: true 它解决了必须存在的错误

错误按摩

我正在通过 rails 安装以下功能,并且由于验证没有保存记录。 我听说optional: true允许保存 nil 记录,但它没有保存optional: true record 没有 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 否则将需要关联对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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