-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharticles_controller.rb
62 lines (51 loc) · 1.29 KB
/
articles_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ArticlesController < ApplicationController
before_action :authorized, only: [:new, :create, :upvote, :downvote]
helper_method :article
def index
@articles = Article.order(created_at: :desc).page(params[:page]).per(20)
@user_votes = Vote.where(user: current_user, votable: @articles.to_a).index_by(&:votable_id)
end
def show
@comments = article.comments.without_parent.order(created_at: :desc)
@comment = Comment.new
end
def upvote
vote(1)
respond_to do |format|
format.json { render json: {new_score: article.score} }
end
end
def downvote
vote(-1)
respond_to do |format|
format.json { render json: {new_score: article.score} }
end
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
article.user = current_user
if article.save
redirect_to article
else
render :new, status: :unprocessable_entity
end
end
private
def article
@article ||= Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :link)
end
def vote(value)
vote = article.votes.find_or_initialize_by(user: current_user)
if vote.value == value
vote.update(value: 0)
else
vote.update(value: value)
end
end
end