DEV Community

Brittany
Brittany

Posted on

Day 66 : #100DaysofCode - Creating a Follow/Unfollow in Rails

I created a follow/unfollow method in my rails application. It wasn't that difficult to implement, but the logic took a moment.

Migration

First I created the Follows Migration.

class CreateFollows < ActiveRecord::Migration[6.0]
  def change
    create_table :follows do |t|
      t.belongs_to :user
      t.belongs_to :post

      t.timestamps
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Models

Then I updated the models for user and post.

post.rb

 #Follow Section
    has_many :follows, dependent: :destroy
    has_many :users, through: :follows
Enter fullscreen mode Exit fullscreen mode

user.rb

has_many :follows
Enter fullscreen mode Exit fullscreen mode

follow.rb

class Follow < ApplicationRecord
    belongs_to :company
    belongs_to :user

    validates_uniqueness_of :user_id, :scope => :post_id
end
Enter fullscreen mode Exit fullscreen mode

Views

Then I wanted to display a follow/unfollow button based off if a user was following or not in the view.

<%# Follow this post%>
<% if current_user.followed?(@post) %>
  <%= button_to "unfollow", post_follows_path(@post.id), class: "myButton" %>
<% else %>
  <%= button_to "follow", post_follows_path(@post.id), class: "myButton"  %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Model Method

I created the followed? method inside of my user controller so that it would work with the current_user logged in.

  def followed?(post)
      follow = Followed.find_by(user_id: self.id, post_id: post.id)
    end 
Enter fullscreen mode Exit fullscreen mode

Routes (nested)

Lastly, I updated my route to have a nested route for the post:

 resources :posts do 
    resources :follows, only: [:index, :create]
  end  
Enter fullscreen mode Exit fullscreen mode

And that is it, a simple follow/unfollow function on my rails application.

Thanks for reading!

Sincerely,
Brittany

Song of the day: A throwback 💕

Top comments (0)