如何解决我不明白“可选:正确”如何在轨道上工作?
我无法理解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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。