I'm a casual Ruby On Rails developer in Geneva, Switzerland. This is my Rails tips repository, mainly intended to myself and my deficient memory.


Text

Oct 22, 2010
@ 11:01 am
Permalink

2 notes

Factory girl and habtm associations

Considering the following models:

  
    class Seminar < ActiveRecord::Base
      has_many :hostings, :dependent=> :destroy
      has_many :hosts, :through => :hostings
      accepts_nested_attributes_for :hostings, :allow_destroy => true
      validate :presence_of_hostings
      
      private
        def presence_of_hostings
          self.errors.add("Hosts",": Seminar should have at least 1 host") if self.hostings.blank?
        end
    end
    
    class Hosting < ActiveRecord::Base
      belongs_to :host
      belongs_to :seminar
      validates :host_id, :presence => true, :uniqueness => {:scope => :seminar_id}
    end
    
    class Host < ActiveRecord::Base
      has_many :hostings
      has_many :seminars, :through => :hostings
    end
  

Set your factories as:

  
    Factory.sequence :name do |n|
      "#{n}"
    end
    
    Factory.define :seminar do |s|
      s.hostings_attributes {{:one => {:host_id => Factory(:host).id}}}
    end
    
    Factory.define :hosting do |i|
      i.association :host
      i.association :seminar
    end
    
    Factory.define :host do |i|
      i.name { 'host_'+Factory.next(:name) }
      i.email { |h| 'host_'+Factory.next(:name)+'@email.com' }
    end
  

If you set your seminar factory as:

  
    Factory.define :seminar do |s|
      s.hostings{ |a| [a.association :hosting]}
    end
  

… you get a SystemStackError: stack level too deep because because of the circular dependency between hosting and seminar.

  1. myrailstips posted this