Je vais vous montrer comment implémenter la fonction similaire dans Rails. Le système terminé ressemble à ce qui suit.
$ rails g model like user_id:integer post_id:integer
$ rails db:migrate
Décrivez les éléments suivants pour chacun et définissez l'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
Écrivez ce qui suit en bas de application.scss
application.scss
@import "bootstrap-sprockets";
@import "bootstrap";
La partie suivante de application.js
application.js
//= require rails-ujs
//= require turbolinks
//= require_tree .
De
application.js
//= require rails-ujs
//= require jquery
//= require bootstrap-sprockets
//= require_tree .
Réécrivez dans.
html:index.html.erb
<div class="container">
<h1>Liste des 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>
C'est tout ce qu'on peut en dire.
https://qiita.com/soehina/items/a68ab66da3ea1d260301
Recommended Posts