关联字段的强制验证

Forced validations for associated fields

我正在使用 rails 5.0.0.1

当我提交表单时,相关字段的验证就会生效。

我有GigUserCategory和其他模型

我正在使用 devise 进行用户身份验证

千兆机型

class Gig < ActiveRecord::Base
  has_many :proposals
  belongs_to :category
  has_many :abilities
  has_many :skills, through: :abilities
  belongs_to :user
end

用户模型

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :gigs
  has_many :proposals
end

类别模型

class Category < ActiveRecord::Base
  has_many :gigs
end

当我尝试在控制台中创建演出时,事务回滚。

错误信息是

["Category must exist", "User must exist"]

感谢您的帮助。提前致谢。

在 rails 5 中,当您添加 belongs_to 时,它会使该字段成为必填项。试试这个

belongs_to :user, optional: true