Search code examples
ruby-on-railsdeviserails-activerecorddevise-confirmable

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


I want the user to confirm their email before they add/edit their profile (it's a really big profile). On the POST /users(.:format) devise/registrations#create page, I get the following errors:

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

The model has these relations:

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

I also specifically added on: :update to allow the user to be created without them, but require them when they are ready to edit their profile:

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

So how do I register/create a new user without needed the relations? It works for editing/updating an existing user.


Solution

  • In rails 5 a belongs_to relationship requires the associated record, or records, be present. So the validation error is getting triggered because those records are not present when first saving the user. However, you can make them optional and I believe that should solve your issue.

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