I have this rails model association (has_many :through)
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, :through => :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
I only have 3 roles (for now) in my application, each role :name is unique. So the role database contains 3 entries for now, user, admin, moderator.
How can I create factories so that I can create users, admins, and moderators and their roles ?
I would love to do something like:
(the role :name is checked for uniqueness, so it shouldn’t create 1 role entry per user, it should instead create 1 assignment to a role per user.)
# Create my roles
FactoryGirl.create(:role, :name => 'admin')
FactoryGirl.create(:role, :name => 'user')
FactoryGirl.create(:role, :name => 'moderator')
# Create 10 users and 10 moderators assuming that the username is sequential or something
for i in 0..10
user = FactoryGirl.create(:user) # user.roles.first.name.eql? 'user' #should be true
mod = FactoryGirl.create(:moderator) # mod.roles.first.name.eql? 'moderator' #should be true
end
How would you create the factories to model this association with FactoryGirl ?
I contacted Josh Clayton (maintainer of Factory Girl) about this issue, he was kind to reply the following:
So in the end I solved the issue by doing something like:
Just forgot about the “assignment” intermediate table.