user1438150
user1438150

Reputation: 175

Association created event

A user belongs_to an company and a company has_many users. Lets say in my company controller create method I do:

company = @current_user.create_company(company_params)

Once a company was created, I want to be able to set the user to "user.admin = true" . What is the best way to do this?

I've tried the following in my company controller. But company doesn't have any users even after_commit callback in org.

class Company < ActiveRecord::Base
    after_commit :set_creator_as_admin
    has_many :users

    private

    def set_creator_as_admin
      self.users.first.set_role_admin
    end
end

Would this be a good time to use an object service? Also is there a way to get this working without an object service?

Upvotes: 0

Views: 38

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

Since admin property belongs to user, we should update it via user instead. Make it simple, we can use like this:

@current_user.build_company(company_params)
@current_user.admin = true
@current_user.save!

The company & use will be updated once.

Upvotes: 1

Related Questions