I created a follow/unfollow method in my rails application. It wasn't that difficult to implement, but the logic took a moment.
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
Then I updated the models for user and post.
#Follow Section has_many :follows, dependent: :destroy has_many :users, through: :follows
class Follow < ApplicationRecord belongs_to :company belongs_to :user validates_uniqueness_of :user_id, :scope => :post_id end
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 %>
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
Lastly, I updated my route to have a nested route for the post:
resources :posts do resources :follows, only: [:index, :create] end
And that is it, a simple follow/unfollow function on my rails application.
Thanks for reading!
Song of the day: A throwback 💕