Using the Faker Gem

As I progressed forward with this project, I found that I needed a larger sample of users, events, and event invitations in order to move forward. The Faker gem is the perfect tool for the job. Check out the full db/seeds.rb file for this project here.

I had some difficulty creating many unique invitations. The Invitation Table is a join table holding the User’s ID as ‘attendee_id’, an Event ID as ‘attended_event_id’, and a ‘response’ to that invitation. This row must be unique; the user can not be invited to the event multiple times.

I began the loop by picking a random user, identified by the ‘attendee_id’ on the join table, using the Faker random unique number generator. For each random user picked, I iterate through each Event and create an invitation for the attendee_id with a random ‘response’ selected from the response array.

50.times do |n|
  response = ['yes', 'no', 'maybe', 'invited']
  attendee_id = User.find(Faker::Number.unique.between(1, User.count))

  Event.count.times do |n|
    attended_event_id = Event.find(n + 1)
    Invitation.create!(attendee: attendee_id,
                       attended_event: attended_event_id,
                       response: response.sample)
  end
end

The result is 50 users that are invited to every. Each event will have a random number of each reply. Though the same users appear on each event, the goal to get a variety of replies is achieved and I can begin testing integration and formatting style appropriately.

Advertisements