I have a Rails 7 app where my registration form only contains 2 fields:
- Company Name
The registration involves the following models:
- Company
- Account
- User
The associations involved are:
- A company has one account (embedded association),
- And an account can have one or multiple users (referenced association)
The idea is that upon registering, the controller should create:
- a Company document created with the name from the form, and embed the Account document
- an Account document, embedded in Company, with a Users Array referencing the user created
- a User document created with the email used in the registration form.
Everything works as expected so far except the Users reference association. Regardless of what I try, the Account document embedded in the Company document does not show a users array with references to my User.
I might be missing something obvious, but I can't see the forest for the trees anymore.
RegistrationsController
def create
@account, @user, @company = Account.new, User.new, Company.new
@user.email = registration_params[:user][:email]
@account.users << @user
@company.name, @company.account = registration_params[:company][:name].squish, @account
puts "registration valid checks"
puts @company.valid?, @account.valid?, @user.valid? #All valid
if @user.save and @account.save and @company.save
flash[:email] = @user.email
redirect_to "/thank-you", notice: "Account was successfully created."
else
render :new, status: :unprocessable_entity
end
end
Account Model
class Account
include Mongoid::Document
include Mongoid::Timestamps
field :creation_date, type: DateTime
has_many :users
embedded_in :company
validates_presence_of :users, on: :create #Does not yield errors
end
User Model
class User
include Mongoid::Document
include Mongoid::Timestamps
field :email, type: String
belongs_to :account
validates :email, presence: true, uniqueness: { case_sensitive: false }, on: :create
end
And yet, when looking at the Company document saved in Mongo, the output looks like this:
[...]
name: 'xxx',
account: {
_id: xxx,
updated_at: xxx,
created_at: xxx
}
[...]
Where I would expect something along the lines of:
[...]
name: 'xxx',
account: {
_id: xxx,
updated_at: xxx,
created_at: xxx,
users: [{_id:'xxxx'}]
}
[...]
Any help would be massively appreciated.
Thanks