Rails: Make parent association optional only on first create

40 Views Asked by At

I have a user and a company model

class Company < ApplicationRecord
    has_many :users
    #name
end

class User < ApplicationRecord
    belongs_to :company
    #email, first_name, #last_name
end

I want to create the company and the first user in that company with the registration form.

After they are registered the first user then adds more users to their company.

Seems like accepts_nested_attributes_for could be the way to go

class User < ApplicationRecord
    belongs_to :company
    accepts_nested_attributes_for :company
end

then in my controller

def user_company_params
    params.require(:user).permit( 
        :email, 
        :first_name, 
        :last_name, 
        company_attributes: [
            :name
        ])
end

User.create( user_company_params )

This yields the following error..

Validation failed: Company must exist

which i can solve by adding this to my users model

belongs_to :company, optional: true

However when the user then proceeds to add more users to the comany in an ideal world the company association would be NOT be optional

then it occured to me to do it the other way round..

class Company < ApplicationRecord
    has_many :users
    accepts_nested_attributes_for :users
end

class User < ApplicationRecord
    belongs_to :company
end

then in the registrations controler

def company_user_params
   params.require(:company).permit( 
        :name,
        :ident,
        users_attributes: [
            :email, 
            :first_name, 
            :last_name, 
            :password
        ]
   )
end

Company.create( company_user_params )

However if i wanted to log the user in after creation i'd have to do something like this...

Company.create( company_user_params )
user = Company.users.first
login( user )

which feels a bit icky.

Anyone got any better ways to approach this??

0

There are 0 best solutions below