Search code examples
ruby-on-railsrubyruby-on-rails-4fabrication-gem

Rails Fabrication gem association creating many objects


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.


Solution

  • 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.