Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Rails: Skip after_create

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.

Upvotes: 1

Views: 2339

Answers (1)

Vishal Taj PM
Vishal Taj PM

Reputation: 1359

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

Upvotes: 5

Related Questions