I will show you how to implement the like function in Rails. The completed system looks like the following.
--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
$ rails g model like user_id:integer post_id:integer
$ rails db:migrate
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
routes.rb
resources :posts, shallow: true do
resources :likes, only: [:create, :destroy]
end
post.rb
def liked_by?(user)
likes.where(user_id: user.id).exists?
end
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
Gemfile
gem 'bootstrap-sass', '~> 3.3.6'
gem 'jquery-rails'
$ bundle install
$ mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss
Write the following at the bottom of application.scss
application.scss
@import "bootstrap-sprockets";
@import "bootstrap";
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.
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.
https://qiita.com/soehina/items/a68ab66da3ea1d260301
Recommended Posts