Yuto Blog

Yuto Blog

Ruby on Rails で vote (like, dislike, unvote) 出来るアプリケーションを作る (acts_as_votable)

>>> デモサイトはこちらです <<<

>>> 参考:Bootstrapの開発環境を自動的に作る <<<

このアプリケーションでは、ユーザーはLike、Dislike、またはUnvote出来る機能を追加したいと思います。

Screen Shot 2015-05-31 at 23.48.46.png

Gemfile
gem 'acts_as_votable'
gem 'devise'

ユーザー登録を作成

Deviseをインストール:

rails g devise:install

ユーザーモデルを作る:

rails g devise User

ユーザー登録のリンクを付ける
app/views/layouts/application.html.slim
- if user_signed_in?
  li Signed in as #{current_user.email}
  li = link_to 'Sign out', destroy_user_session_path, method: :delete
- else
  li = link_to 'Sign up', new_user_registration_path
  li = link_to 'Sign in', new_user_session_path

記事を作成

ArticleのScaffoldを作る

rails g scaffold Article title content:text

データベースをマイグレート:

rake db:migrate

これからVoteのシステムを作ります

config/routes.rb
  resources :articles do
    member do
      put 'like'    => 'articles#like'
      put 'dislike' => 'articles#dislike'
      put 'unvote'  => 'articles#unvote'
    end
  end

ユーザーはVoteします

app/models/user.rb
acts_as_voter

記事はVoteされます

app/models/article.rb
acts_as_votable
app/controllers/articles_controller.rb
  before_action :set_article, only: [:show, :edit, :update, :destroy, :like, :dislike, :unvote]

  def like
    @article.liked_by current_user
    redirect_to @article, notice: "You liked this!"
  end

  def dislike
    @article.disliked_by current_user
    redirect_to @article, notice: "You disliked this!"
  end

  def unvote
    @article.unvote_by current_user
    redirect_to @article, notice: "You unvoted this!"
  end

記事に関するメソッド:

Voteを数える:@article.votes_for.size

Likeを数える:@article.get_likes.size

Dislikeを数える:@article.get_dislike.size

Likeされたユーザー:@article.votes_for.up.by_type(User).voters

Dislikeされたユーザー:@article.votes_for.down.by_type(User).voters

ユーザーに関するメソッド:

Likeしたかどうかを確認:current_user.voted_up_on? @article

Dislikeしたかどうかを確認:current_user.voted_down_on? @article

Likeした記事:current_user.votes.up.for_type(Article).votables

Dislikeした記事:current_user.votes.down.for_type(Article).votables

app/views/articles/show.html.slim
= link_to 'Like', like_article_path(@article), method: :put
= link_to 'Dislike', dislike_article_path(@article), method: :put
= link_to 'Unvote', unvote_article_path(@article), method: :put
Created by Yuto at 2022-01-21 17:42
0
Like this article
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.