Skip to content

Instantly share code, notes, and snippets.

@gmcclure
Created May 8, 2013 03:49
Show Gist options
  • Save gmcclure/5538047 to your computer and use it in GitHub Desktop.
Save gmcclure/5538047 to your computer and use it in GitHub Desktop.
an attempt to model a has_many :through with factory girl ...
# app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
has_many :staff_memberships
has_many :publications, :through => :staff_memberships
end
# app/models/publication.rb
class Publication < ActiveRecord::Base
attr_accessible :description, :title
has_many :staff_memberships
has_many :users, :through => :staff_memberships
validates :users, :length => { :minimum => 1, :too_short => "a publication must have at least one user" }
end
# app/models/staff_membership.rb
class StaffMembership < ActiveRecord::Base
attr_accessible :publication_id, :user_id
belongs_to :user
belongs_to :publication
end
# test/factories.rb
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "user#{n}@suremail.info" }
# encrypted_password { User.new.send(:password_digest, 'motorcycle!') }
password "motorcycle!"
password_confirmation "motorcycle!"
confirmed_at { Time.now }
end
factory :publication do
title "Entasis"
description "A small literary journal."
after :create do |pub|
pub.users << FactoryGirl.create(:user)
end
end
factory :staff_membership do
user
publication
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment