2018-02-21 12:09:22 +00:00
|
|
|
class V1::ArticlesController < ApplicationController
|
2018-02-19 16:03:07 +00:00
|
|
|
before_action :set_article, only: [:show, :update, :destroy]
|
|
|
|
|
skip_before_action :authorize_request, only: [:index, :show]
|
|
|
|
|
|
|
|
|
|
# GET /articles
|
|
|
|
|
def index
|
2018-02-22 11:47:14 +00:00
|
|
|
posts_per_page = 10
|
|
|
|
|
current_page = params[:page]
|
|
|
|
|
@article = Article.all.order(created_at: :desc).paginate(page: current_page, per_page: 10)
|
|
|
|
|
total_pages = (@article.count / posts_per_page).ceil
|
|
|
|
|
|
|
|
|
|
pagination = {
|
2018-02-22 14:28:22 +00:00
|
|
|
"current_page": current_page.to_i == 0 ? 1 : current_page,
|
2018-02-22 11:47:14 +00:00
|
|
|
"last_page": total_pages,
|
2018-02-22 14:28:22 +00:00
|
|
|
"next_page": "#{current_page.to_i < total_pages.to_i ? (current_page.to_i+1) : (current_page)}",
|
|
|
|
|
"prev_page": "#{current_page.to_i > 1 ? (current_page.to_i-1) : (current_page)}"
|
2018-02-22 11:47:14 +00:00
|
|
|
}
|
2018-02-22 16:00:39 +00:00
|
|
|
json_response({articles: @article.as_json(include: [:user, :comments]), pagination: pagination})
|
2018-02-19 16:03:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# POST /articles
|
|
|
|
|
def create
|
|
|
|
|
@article = current_user.articles.create!(article_params)
|
|
|
|
|
json_response(@article, :created)
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# GET /articles/:id
|
|
|
|
|
def show
|
2018-02-21 11:40:37 +00:00
|
|
|
json_response(@article.to_json(include: :user))
|
2018-02-19 16:03:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# PUT /articles/:id
|
|
|
|
|
def update
|
|
|
|
|
@article.update(article_params)
|
|
|
|
|
head :no_content
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# DELETE /articles/:id
|
|
|
|
|
def destroy
|
|
|
|
|
@article.destroy
|
|
|
|
|
head :no_content
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
|
|
def article_params
|
|
|
|
|
# whitelist params
|
2018-02-22 11:47:14 +00:00
|
|
|
params.permit(:title, :post, :page)
|
2018-02-19 16:03:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def set_article
|
2018-02-21 11:40:37 +00:00
|
|
|
@article = Article.find(params[:id])
|
2018-02-19 16:03:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
end
|