Last active
December 18, 2021 21:14
-
-
Save kdmgs110/2e9f547aa73b29eb87990382786b267c to your computer and use it in GitHub Desktop.
【Ruby on Rails 】act as votableの使い方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#設定 | |
- user has posts | |
- user has comments | |
#やりたいこと | |
- Likeしてみる | |
- Likeを取り消す | |
- Likeの数を調べる | |
- likeしたものを一覧できるページを作成する | |
- LikeしてたらLike取り消し、LikeしてなかったらLikeを表示 | |
- Like済みは色が塗られていて、Likeされていない場合は色が塗られていない(font-awesomeで実装) | |
#posts_controller.rb | |
def upvote | |
@post = Post.find(params[:id]) | |
@post.liked_by current_user | |
redirect_to @post | |
end | |
def downvote | |
@post = Post.find(params[:id]) | |
@post.unliked_by current_user | |
redirect_to @post | |
end | |
# post.rb | |
class Post < ActiveRecord::Base | |
acts_as_votable | |
belongs_to :user | |
has_many :comments | |
end | |
# config/routes.rb | |
resources :posts do | |
member do | |
put "like", to: "posts#upvote" | |
put "dislike", to: "posts#downvote" | |
end | |
end | |
#show.html.erb | |
<div>お気に入り数(<%= @posts.votes_for.size %>) </div> #likeの数を取り出す | |
<%= link_to "お気に入り", like_post_path(@posts), method: :put %> #likeしてみる | |
<%= link_to "取り消す", dislike_post_path(@posts), method: :put %> #likeを取り消す | |
(2) 自分のlikeしたページの一覧を表現 | |
#posts_controller.rb | |
def like | |
@posts = current_user.votes.up.for_type(User).votables | |
end | |
#routes.rb | |
resources :posts do | |
member do | |
get 'like', to: "posts#like" | |
end | |
end | |
#posts/like.html.erb | |
<%= @posts.each do |post| %> | |
<%= %> | |
<% end %> | |
#いいね数をカウントする | |
<%= post.votes_for.size %> | |
#いいねしてたらいいねを表示、いいねしてなかったらいいねを表示 | |
<% unless current_user.voted_for? comment %> | |
<%= link_to "お気に入り", like_comment_path(comment), method: :put %>(<%= comment.votes_for.size %>) | |
<% else %> | |
<%= link_to "取り消す", dislike_comment_path(comment), method: :put %> | |
<% end %> | |
#likeボタンの実装 | |
<% unless current_user.voted_for? comment %> | |
<%= link_to like_comment_path(comment), method: :put do%><i class="fa fa-star-o colored-star" aria-hidden="true"></i><% end %> <%= comment.votes_for.size %> | |
<% else %> | |
<%= link_to dislike_comment_path(comment), method: :put do%><i class="fa fa-star uncolored-star" aria-hidden="true"></i><%end%> <%= comment.votes_for.size %> | |
<% end %> | |
#参考URL | |
http://stackoverflow.com/questions/15012276/acts-as-votable-thumbs-up-down-buttons | |
http://stackoverflow.com/questions/22949440/act-as-votable-list-who-voted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment