factory-girl-rails
many-to-many
# models/
class Role < ActiveRecord::Base
has_and_belongs_to_many :admins
end
class Admin < ActiveRecord::Base
has_and_belongs_to_many :roles
end
# factories/
FactoryGirl.define do
factory :role do
name "manager"
end
end
FactoryGirl.define do
factory :admin do
account FFaker::Internet.email
password FFaker::Lorem.word
nickname FFaker::Name.name
end
end
# usage:
role1 = create(:role, name: "developer")
role2 = create(:role, name: "tester")
admin = create(:admin_with_role, roles: [role1, role2])
#note: you must assign an array to has_many associations, e.g. roles:[role1], otherwise it will error out something like undefined method `each' for....
puts admin.roles.inspect
#=> #<ActiveRecord::Associations::CollectionProxy [#<Role id: 139, name: "developer", created_at: "2015-08-23 02:39:34", updated_at: "2015-08-23 02:39:34">, #<Role id: 140, name: "tester", created_at: "2015-08-23 02:39:34", updated_at: "2015-08-23 02:39:34">]>
puts role1.admins.inspect
#=> #<ActiveRecord::Associations::CollectionProxy [#<Admin id: 147, account: "shyann@armstrong.com", password: "placeat", nickname: "Sylvia Weber", created_at: "2015-08-23 02:39:34", updated_at: "2015-08-23 02:39:34", restaurant_id: nil>]>
puts role2.admins.inspect
#=> #<ActiveRecord::Associations::CollectionProxy [#<Admin id: 147, account: "shyann@armstrong.com", password: "placeat", nickname: "Sylvia Weber", created_at: "2015-08-23 02:39:34", updated_at: "2015-08-23 02:39:34", restaurant_id: nil>]>