1

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.

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92

1 Answers1

5

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
Vishal Taj PM
  • 1,339
  • 11
  • 23
  • I literally just figured this out as I saw your response. For some reason I thought `attr_accessor` was gone in Rails 4, but it's useful in this case – Jeremy Thomas Apr 05 '17 at 19:44
  • You're probably thinking of `attr_accessible`, which is indeed gone in Rails 4. `attr_accessor` is a straight-Ruby feature. – Corey Woodcox Apr 05 '17 at 22:22
  • @CoreyWoodcox yes, i have heard the same but haven't found it on official Rails Doc. please share your findings. – Vishal Taj PM Apr 06 '17 at 04:03