I'm trying to build factories for relatively complex models.
I have a Pressroom model, which belongs to Source, and Source has many Pressrooms. When creating the Source, if pressrooms is empty, an initial pressroom is created in an after_create filter. The pressroom site must be unique per source.
class Source
has_many :pressrooms
after_create :create_initial_pressroom! # if pressrooms.empty?
...
end
class Pressroom
belongs_to :source
# source.pressrooms.map(&:site) should have unique elements
validate_on_create :check_unique_site
end
This leads to my problem: My Pressroom.make
fails, because it builds a Source, which has no pressrooms, so the after_create
callback creates one, and when the Pressroom.make
tries to finish up, its site is not unique. I don't want to create two pressrooms when I run Pressroom.make
My attempt to solve this is to make the source association in the pressroom blueprint reference the pressroom. Sort of what Source.create :pressrooms => [Pressroom.new]
would do.
Pressroom.blueprint do
source { Source.make :pressrooms => [self] }
site { source.site }
end
Unfortunatly, self
is not yet a Pressroom. It's an instance of Machinist::Lathe, so I get an ActiveRecord::AssociationTypeMismatch exception.
I'm a bit of a newbie when it comes to factories and Machinist. I don't want to have to change the business logic, and I want to be able to cleanly make pressrooms with Pressroom.make
without making two pressrooms in the process. If switching to factory-girl would help, I'm open to that.
I'd be grateful for any ideas on how to solve this.