2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ユーザー登録機能つき投稿サイト⑤(いいね機能追加)

Posted at

act as votableをつかう。

1,gem 'acts_as_votable', '~> 0.11.1' → bundle

2、votes tableを作成。
rails generate acts_as_votable:migration
3,post モデルにacts_as_votableを追加。
4,ルーティングに以下を記述。

memberに関しては2.10.1 メンバールーティングを追加するを参照。

routes.rb
resources :posts do 
    member do
      get "like", to: "posts#upvote"
      get "dislike", to: "posts#downvote"
    end
    resources :comments 
  end

これにより「/posts/:id/like」と「/posts/:id/dislike」が作成される。

5,posts_controller.rbでbefore_actionとアクションを設定。

posts_controller.rb
before_action :find_post, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index,:show]

:
:
:
:
:
:

def upvote
    @post.upvote_by current_user
    redirect_back(fallback_location: root_path)
end
    
def downvote
    @post.downvote_by current_user
    redirect_back(fallback_location: root_path)
end

7,posts/show.html.erbとposts/index.html.erbに以下を追加

posts/show.html.erb
<p><%= link_to "いいね!", like_post_path(@post), method: :get  %>:<%= @post.get_upvotes.size %></p>
<p><%= link_to "ダメだね!", dislike_post_path(@post),method: :get %>:<%= @post.get_downvotes.size %></p>
posts/index.html.erb
<p>いいね!:<%= post.get_upvotes.size %></p>
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?