I have an Account model that accepts nested attributes for a user model. An Account has_many users. So a user cannot exist without an account. I wrote this validation:
# users.rb
validates :account_id, presence: true, numericality: { only_integer: true }
During sign up, a user fills the account form, and a nested user form. However, because the account does not yet exist, my tests are failing with this error:
#<ActiveModel::Errors: ... @base=#<Account id: nil, title: "ACME Corp", subdomain: "acme1", created_at: nil, updated_at: nil>, @messages={:"users.account_id"=>["can't be blank"]}>
I always want to ensure a valid account id exists for the user, unless the user is being created via a nested form in Accounts#new. In other words, when an Account is being created at the same time, in which case no account id exists yet to provide to the user.
Is there a way to do this?
It may be a moot point since all new users will be created via a current_account object, a la current_account.users.build. But I want to be sure.
In User model:
In Account model:
This simply validates that the parent object is present – even if it hasn’t been saved yet.