/app/controllers/blogs_controller.rb
Ruby | 86 lines | 62 code | 10 blank | 14 comment | 3 complexity | 288e58cbc1332c325a16b7152dba168d MD5 | raw file
- class BlogsController < ApplicationController
- before_action :authenticate_user!, only: [:edit, :new, :update, :destroy]
- before_action :set_blog, only: [:show, :edit, :update, :destroy]
- # GET /blogs
- # GET /blogs.json
- def index
- if params[:q].present?
- @q = Blog.ransack(params[:q])
- @blogs = @q.result(distinct: true).order('created_at DESC')
- elsif params[:tag].present?
- @blogs = Blog.tagged_with(params[:tag]).order('created_at DESC')
- else
- @blogs = Blog.all.order('created_at DESC')
- end
- end
- # GET /blogs/1
- # GET /blogs/1.json
- def show
- end
- # GET /blogs/new
- def new
- @blog = Blog.new
- end
- # GET /blogs/1/edit
- def edit
- authorize @blog
- end
- # POST /blogs
- # POST /blogs.json
- def create
- @blog = Blog.new(blog_params)
- @blog.user = current_user
- respond_to do |format|
- if @blog.save
- format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
- format.json { render :show, status: :created, location: @blog }
- else
- format.html { render :new }
- format.json { render json: @blog.errors, status: :unprocessable_entity }
- end
- end
- end
- # PATCH/PUT /blogs/1
- # PATCH/PUT /blogs/1.json
- def update
- authorize @blog
- respond_to do |format|
- if @blog.update(blog_params)
- format.html { redirect_to @blog, notice: 'Blog was successfully updated.' }
- format.json { render :show, status: :ok, location: @blog }
- else
- format.html { render :edit }
- format.json { render json: @blog.errors, status: :unprocessable_entity }
- end
- end
- end
- # DELETE /blogs/1
- # DELETE /blogs/1.json
- def destroy
- authorize @blog
- @blog.destroy
- respond_to do |format|
- format.html { redirect_to blogs_url, notice: 'Blog was successfully destroyed.' }
- format.json { head :no_content }
- end
- end
- private
- # Use callbacks to share common setup or constraints between actions.
- def set_blog
- @blog = Blog.friendly.find(params[:id])
- end
- # Never trust parameters from the scary internet, only allow the white list through.
- def blog_params
- params.require(:blog).permit(:title, :content, :publish, :tag_list, :image_url)
- end
- end