Rails: Skip after_create

2.1k Views Asked by At

I have 2 models:

class User < ActiveRecord::Base
    has_one :client
end

class Client < ActiveRecord::Base
    belongs_to :user
end

and I normally create a user first, and have an after_create filter, to create the client after the user has been created.

after_create :create_client

I have a new case where the client exists, and I want to create the user after the client already exists. In this case, when I create the user I'd like to skip the after_create filter.

I understand that I'll need after_create :create_client, unless: ____ but I'm not sure how to distinguish this.

1

There are 1 best solutions below

3
Vishal Taj PM On BEST ANSWER

For this case you can create a instance variable using attr_accessor

class User < ActiveRecord::Base
  attr_accessor :has_client
  ...
end

and you can assign boolean value to this variable and restrict after_create with if condition

class User < ActiveRecord::Base
  ...
  after_create :create_client, unless: :has_client
  ...
end