Rails Fabrication gem association creating many objects

1k Views Asked by At

I have two models with a simple has_many association

class Usuario < ActiveRecord::Base
  has_many :publicaciones, dependent: :destroy
end

class Publicacion < ActiveRecord::Base
  belongs_to :usuario, dependent: :destroy
  validates_presence_of :usuario
end

And these are the fabricators

Fabricator(:usuario_con_10_publicaciones) do
  nombre { FFaker::NameMX.name }
  publicaciones(count: 10)
end

Fabricator(:publicacion) do
  texto { FFaker::Lorem.paragraphs }
  usuario
end

When I use the second one it works fine, it creates one Publicacion and one Usuario

> a = Fabricate :publicacion
> Usuario.count
=> 1
> Publicacion.count
=> 1

But when I use the first one, it creates ten Publicaciones but eleven Usuarios, with all the Publicaciones associated just with the last one.

> u = Fabricate :usuario_con_10_publicaciones
> Usuario.count
=> 11
> Publicacion.count
=> 10

Shouldn't it create just one Usuario and ten Publicaciones?

Thanks for your help.

2

There are 2 best solutions below

0
Paul Elliott On BEST ANSWER

Steve is right about what's going on. Another solution is to suppress the creation of the usario in the publicaciones.

Fabricator(:usuario_con_10_publicaciones) do
  nombre { FFaker::NameMX.name }
  publicaciones(count: 10) { Fabricate.build(:publicacion, usuario: nil) }
end

ActiveRecord will properly associate them for you when the tree is persisted.

1
SteveTurczyn On

The problem is that when you create the usario it creates 10 publicaciones but every publicaciones fabrication creates one usario

You can use transients to suppress the default creation of the new usario records.

Fabricator(:usuario_con_10_publicaciones) do
  nombre { FFaker::NameMX.name }
  publicaciones(count: 10) { Fabricate(:publicacion, no_usario: true) }
end

Fabricator(:publicacion) do
  transient :no_usario
  texto { FFaker::Lorem.paragraphs }
  usuario { |attrs| Fabricate(:usario) unless attrs[:no_usario] }
end