Cuộc sống Nhật Bản
Yuto Blog

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

Nội dung chính

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

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

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

Screen Shot 2015-05-31 at 23.48.46.png

Copy Gemfile
1
2
gem 'acts_as_votable'
gem 'devise'

ユーザー登録を作成

Deviseをインストール:

rails g devise:install

ユーザーモデルを作る:

rails g devise User

ユーザー登録のリンクを付ける
Copy app/views/layouts/application.html.slim
1
2
3
4
5
6
- 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のシステムを作ります

Copy config/routes.rb
1
2
3
4
5
6
7
  resources :articles do
    member do
      put 'like'    => 'articles#like'
      put 'dislike' => 'articles#dislike'
      put 'unvote'  => 'articles#unvote'
    end
  end

ユーザーはVoteします

Copy app/models/user.rb
1
acts_as_voter

記事はVoteされます

Copy app/models/article.rb
1
acts_as_votable
Copy app/controllers/articles_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  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

Copy app/views/articles/show.html.slim
1
2
3
= 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
Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé
Rate this article: 4.9/5 (45 ratings)
You didn't rate yet
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.