55 lines
1.3 KiB
Ruby
55 lines
1.3 KiB
Ruby
class V1::ArticlesController < ApplicationController
|
|
before_action :set_article, only: [:show, :update, :destroy]
|
|
skip_before_action :authorize_request, only: [:index, :show]
|
|
|
|
# GET /articles
|
|
def index
|
|
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 = {
|
|
"current_page": current_page,
|
|
"last_page": total_pages,
|
|
"next_page": "/articles?page=#{(current_page.to_i + 1).to_s}",
|
|
"prev_page": "/articles?page=#{(current_page.to_i - 1).to_s}"
|
|
}
|
|
json_response({articles: @article.as_json(include: [:user]), pagination: pagination})
|
|
end
|
|
|
|
# POST /articles
|
|
def create
|
|
@article = current_user.articles.create!(article_params)
|
|
json_response(@article, :created)
|
|
end
|
|
|
|
# GET /articles/:id
|
|
def show
|
|
json_response(@article.to_json(include: :user))
|
|
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
|
|
params.permit(:title, :post, :page)
|
|
end
|
|
|
|
def set_article
|
|
@article = Article.find(params[:id])
|
|
end
|
|
|
|
end
|