我希望用户在添加/编辑他们的个人资料之前确认他们的电子邮件(这是一个非常大的个人资料)。在POST /users(.:format) devise/registrations#create
页面上,我收到以下错误:
3个错误禁止此用户被保存: 国家必须存在 公司必须存在 资金必须存在
模型有这些关系:
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
那么如何在不需要关系的情况下注册/创建新用户?它适用于编辑/更新现有用户。
答案 0 :(得分:1)
在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