如何 create/register 具有 belongs_to 关系的用户模型?

How do I create/register a User model that has a belongs_to relation?

我希望用户在add/edit他们的个人资料(这是一个非常大的个人资料)之前确认他们的电子邮件。在 POST /users(.:format) devise/registrations#create 页面上,我收到以下错误:

3 errors prohibited this user from being saved: Country must exist Company must exist Funds must exist

该模型具有以下关系:

  belongs_to :country
  belongs_to :company
  accepts_nested_attributes_for :company
  belongs_to :funds, class_name: 'Fund'

我还特别添加了 on: :update 以允许在没有他们的情况下创建用户,但在他们准备好编辑个人资料时需要他们:

  validates :country, :funds, :company, presence: true, on: :update
  validates_associated :company, on: :update

那么我如何 register/create 一个不需要关系的新用户?它适用于 editing/updating 现有用户。

在 rails 5 中,belongs_to 关系要求存在关联记录或记录。因此验证错误被触发,因为在第一次保存用户时这些记录不存在。但是,您可以将它们设为可选,我相信这应该可以解决您的问题。

belongs_to :country, optional: true
belongs_to :company, optional: true
accepts_nested_attributes_for :company
belongs_to :funds, class_name: 'Fund', optional: true