Users Vote on Posts-Part 1: Backend

Ruby On Rails Association — Belongs To/ Has Many

Osha Groetz
4 min readApr 3, 2021

Ruby On Rails Steps:

  1. Create a new Rails application: rails new <app-name> -database=postgresql
  2. CD into your app and open it in your text editor
  3. In Terminal run: bundle install & rake db:create
  4. Create migrations from Users, Posts, Votes with terminal command: rails g resource <model_name> (((keep model name singular)))

Migrations:

User Migration
Post Migration
Vote Migration

5. Run your migrations: rake db:migrate

6. Triple check your schema and make sure your tables are set up correctly, and that your votes table has it’s two foreign keys connecting it to posts and users.

Schema:

7. Routes: The resource generator will automatically build routes, but we’ll need to correct them so that they’re set up in the right namespace.

It’s important that votes not only have their own routes, but also live within post routing.

Routes:

8. If you choose to use Serializers in the backend to render json, set those up now. You can always render your json directly in your methods, but this is just incase you prefer serializers.

9. New folder in app: serializers with 3 files: user_serializer.rb, post_serializer.rb, vote_serializer.rb

Serializers:

10. Models: build out 3 models: User, Post, Vote and make sure that you define their correct associations and validations

11. While we build our user model, lets make sure to also uncomment the line: gem ‘bcrypt’, ‘~> 3.1.7’ in our Gem file and re-run: bundle install, for future use of our password_digest encryption. (Along with this, don’t forget has_secure_password in User model.)

Models:

12. Controllers: The controllers will hold all of the CRUD actions that we’ll need. Same as before we’ll need one a controller for each Users, Posts, and Votes. Although the Application controller will not live in the API / V1 folders, the other 3 controllers will. After moving them into these files for namespace conventionality.

File SetUp:

Before:

After:

It’s very important that the Class names in the components that have been moved change to reflect their presence in the new folder/file path. Add Api::V1:: in front of the the controller name.

Controllers:

In my 2 posts before this, I have already set up User Signup/SignIn Frontend and Backend. I won’t repost them here but you can find Part 1 here and Part 2 here.

That all covers the backend for now. Next week, I’ll build the frontend so that users can only vote one time on a post (like or dislike) and the application will keep a running tally of votes. Have a great week!

--

--

Osha Groetz
Osha Groetz

Written by Osha Groetz

Software Engineer. React, Javascript, Typescript, HTML, CSS, Ruby, Ruby On Rails

No responses yet