How to handle foreign key in FactoryGirl
Asked Answered
H

2

15

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.

Huihuie answered 25/7, 2014 at 20:15 Comment(0)
B
26

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

association :followed_by_user, factory: :user
Busman answered 25/7, 2014 at 20:23 Comment(0)
C
5

You don't need so much complexity, use just:

followed_by_user factory: :user

This works like a charm.

Cordell answered 23/3, 2017 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.