Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle foreign key in FactoryGirl

I have a user model and a follower model, such that a user can have many followers. So in schema of follower model I have user_id column and a follower_by_user_id column. So in follower model a user can be followed by many followers. User id's are stored in user_id column and followers id's are whose id's are stored in as followed_by_user_id.

class User < ActiveRecord::Base
 has_many :followed_users, :class_name => 'Follower', :foreign_key => 'user_id'
 has_many :followers, :class_name => 'Follower', :foreign_key => 'followed_by_user_id'

 validates :email, presence: true, format:{ with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}

 validates :name,presence:true
end

Above is user model

class Follower < ActiveRecord::Base
 belongs_to :user
 belongs_to :followed_by_user, :class_name => 'User', :foreign_key => 'followed_by_user_id'

 validates :user, :followed_by_user, presence:true
 validates_associated :user, :followed_by_user
end

above is follower model

FactoryGirl.define do 
factory :user do
  name {Faker::Name.name}
  email {Faker::Internet.email}
end 

factory :follower do
  user
  followed_by_user_id
end

followed_by_user_id is basically a user id only, or we can say user_id is foreign key for followed_by_user_id column. Im plain English followed_by_user_id is an id of an user who is following to some other user. So If any body can help how to include this foreign key relationship in follower factory for follower_by_user_id column?

Thanks in advance.

like image 807
Geek_Akash Avatar asked Jul 25 '14 20:07

Geek_Akash


1 Answers

You can use association in your factory, like this (more info in the docs):

association :followed_by_user, factory: :user
like image 145
rabusmar Avatar answered Sep 29 '22 12:09

rabusmar