DEV Community

Cover image for Sinatra MVC CRUD Bet Tracker
John Glennan
John Glennan

Posted on

Sinatra MVC CRUD Bet Tracker

My first DSL project is complete! This project follows an MVC architecture that is able to create, read, update and delete objects. My web apps scope focuses on the creation of bets and displays them for all users to see. Users are only allowed to create, edit and delete their bets but have the viewing pleasure to see other users placed bets. After table creation/migration it was time to test and seed some data. One of my favorite gems is called Faker. It helped me create fake data and 'seed' it into my project. This gem has so much to offer. You can use it to test relationships to see that they work as expected. Users have many Bets and Bets belong to a User. This relationship fostered by active records macro mechanics, made it possible for me to create users and their associated bets using the seed file (db/seeds.rb). For example:

10.times do 
    User.create!(username: Faker::Name.name, password_digest: BCrypt::Password.create('1234'))
end 

10.times do 
    Bet.create!(amount: rand(100), team: Faker::Sports::Football.team, date: "Today", user: User.offset(rand(10)).first)
end
Enter fullscreen mode Exit fullscreen mode

How exactly do you seed data? You can seed data using a built in rake task 'rake db:seed'. So how do you test these relationships? I used a custom rake task in my rakefile that uses the pry gem.

task :console do 
   Pry.start
end 
Enter fullscreen mode Exit fullscreen mode

I then proceeded to make sure that my relationships were working as expected:

u = User.first
Enter fullscreen mode Exit fullscreen mode

This returned my first User! Perfect! Now to test and see if he has any seeded bets:

Alt Text
Awesome! It worked. I was now able to continue coding and create my controllers and views. To use faker in your project all you need to do is add gem 'faker' to your gemfile. I suggest reading fakers documentation (link: https://github.com/faker-ruby/faker). If you use bundler make sure to bundle install. You can even use IRB to play around with the faker gem. Cheers!

Top comments (0)