Day 66 : #100DaysofCode - Creating a Follow/Unfollow in Rails
Brittany
Posted on August 8, 2020
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
Models
Then I updated the models for user and post.
post.rb
#Follow Section
has_many :follows, dependent: :destroy
has_many :users, through: :follows
user.rb
has_many :follows
follow.rb
class Follow < ApplicationRecord
belongs_to :company
belongs_to :user
validates_uniqueness_of :user_id, :scope => :post_id
end
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 %>
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
Routes (nested)
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!
Sincerely,
Brittany
Song of the day: A throwback 💕
Posted on August 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024