How to implement a like feature in Rails

I will show you how to implement the like function in Rails. The completed system looks like the following. いいね1.gif

environment

Premise

--The login function by devise can be implemented. --The user table is "users", the article table is "posts", and the likes intermediate table is "likes". --Add title to the posts column

Added Like model

$ rails g model like user_id:integer post_id:integer

$ rails db:migrate

Set up an association

Describe the following for each and set the association.

like.rb


  belongs_to :user
  belongs_to :post

user.rb


  has_many :likes, dependent: :destroy

post.rb


  has_many :likes, dependent: :destroy

Set up routing

routes.rb


  resources :posts, shallow: true do
    resources :likes, only: [:create, :destroy]
  end

Create preferred_by? method

post.rb


  def liked_by?(user)
    likes.where(user_id: user.id).exists?
  end

Description of controller

likes_controller.rb


  def create
    like = Like.new(user_id: current_user.id, post_id: params[:post_id])
    @post = like.post
    like.save
    redirect_back(fallback_location: posts_path)
  end

  def destroy
    like = Like.find(params[:id])
    @post = like.post
    like.destroy
    redirect_back(fallback_location: posts_path)
  end

Introduced Bootstrap

Gemfile


gem 'bootstrap-sass', '~> 3.3.6'
gem 'jquery-rails'
$ bundle install

Rename application.css to application.scss

$ mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss

Load Bootstrap into scss

Write the following at the bottom of application.scss

application.scss


@import "bootstrap-sprockets";
@import "bootstrap";

Edit application.js

The following part of application.js

application.js


//= require rails-ujs
//= require turbolinks
//= require_tree .

From

application.js


//= require rails-ujs
//= require jquery
//= require bootstrap-sprockets
//= require_tree .

Rewrite to.

Edit index.html.erb

html:index.html.erb


<div class="container">
  <h1>List of articles</h1>
  <table class="table">
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td>
          <% if post.liked_by?(current_user) %>
            <% like = Like.find_by(user_id: current_user.id, post_id: post.id) %>
            <%= link_to like_path(like), method: :delete do %>
              <span class="glyphicon glyphicon-heart" aria-hidden="true" style="color: red;">
              <span><%= post.likes.count %></span>
            <% end %>
          <% else %>
            <%= link_to post_likes_path(post), method: :post do %>
              <span class="glyphicon glyphicon-heart" aria-hidden="true" style="color: gray;">
              <span><%= post.likes.count %></span>
            <% end %>
          <% end %>
        </td>
      </tr>
    <% end %>
  </table>
</div>

That's all there is to it.

Reference article

https://qiita.com/soehina/items/a68ab66da3ea1d260301

Recommended Posts

How to implement a like feature in Rails
How to implement a like feature in Ajax in Rails
How to implement search functionality in Rails
How to insert a video in Rails
How to implement ranking functionality in Rails
How to easily create a pull-down in Rails
Implement the Like feature in Ajax with Rails.
How to make a follow function in Rails
[Rails] How to implement scraping
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to implement guest login in 5 minutes in rails portfolio
[How to insert a video in haml with Rails]
How to write a date comparison search in Rails
[Rails 6] How to set a background image in Rails [CSS]
[Rails] How to load JavaScript in a specific view
[Rails] How to write in Japanese
Implement a like feature for posts
Implement a contact form in Rails
How to introduce jQuery in Rails 6
[Rails] How to implement star rating
How to install Swiper in Rails
How to display a graph in Ruby on Rails (LazyHighChart)
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to implement date calculation in Java
How to implement Kalman filter in Java
How to change app name in rails
How to use custom helpers in rails
How to use MySQL in Rails tutorial
How to implement coding conventions in Java
Steps to set a favicon in Rails
[rails] How to configure routing in resources
[rails] How to create a partial template
Implement something like a stack in Java
How to implement image posting using rails
How to implement asynchronous processing in Outsystems
How to publish a library in jCenter
How to use credentials.yml.enc introduced in Rails 5.2
[Rails] A simple way to implement a self-introduction function in your profile
I tried to implement Ajax processing of like function in Rails
How to implement a job that uses Java API in JobScheduler
How to rename a model with foreign key constraints in Rails
How to write Rails
[Rails] How to create a graph using lazy_high_charts
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Rails] How to log in with a name by adding a devise name column
How to display a web page in Java
How to implement more than one top page in Rails breadcrumb trail
How to translate Rails into Japanese in general
How to prevent direct URL typing in Rails
[Rails] How to implement unit tests for models
How to run a djUnit task in Ant
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP
How to uninstall Rails
How to implement gem "summer note" in wysiwyg editor in Ruby on Rails
How to update user edits in Rails Devise without entering a password
How to separate .scss by controller in Rails
How to conditionally add html.erb class in Rails
[Rails] How to create a Twitter share button
How to use JQuery in js.erb of Rails6
[Rails] How to easily implement numbers with pull-down