MattZhao/AtRisk

View on GitHub
app/controllers/news_controller.rb

Summary

Maintainability
A
0 mins
Test Coverage
class NewsController < ApplicationController
  before_action :authenticate_user!, :set_news, only: [:show, :edit, :update, :destroy]

  # GET /news
  # GET /news.json
  def index
    @news = News.all
  end

  # GET /news/1
  # GET /news/1.json
  def show
  end

  # GET /news/new
  def new
    if !current_user.admin
      return redirect_to '/messages/no_access'
    end
    @news = News.new
  end

  # GET /news/1/edit
  def edit
    if !current_user.admin
      return redirect_to '/messages/no_access'
    end
  end

  # POST /news
  # POST /news.json
  def create
    if !current_user.admin
      return redirect_to '/messages/no_access'
    end
    
    @news = News.new(news_params)

    respond_to do |format|
      if @news.save
        format.html { redirect_to @news, notice: 'New FAQ entry was successfully created.' }
        format.json { render :show, status: :created, location: @news }
      else
        format.html { render :new }
        format.json { render json: @news.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /news/1
  # PATCH/PUT /news/1.json
  def update
    if !current_user.admin
      return redirect_to '/messages/no_access'
    end
    
    respond_to do |format|
      if @news.update(news_params)
        format.html { redirect_to @news, notice: 'FAQ entry was successfully updated.' }
        format.json { render :show, status: :ok, location: @news }
      else
        format.html { render :edit }
        format.json { render json: @news.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /news/1
  # DELETE /news/1.json
  def destroy
    if !current_user.admin
      return redirect_to '/messages/no_access'
    end
    
    @news.destroy
    
    respond_to do |format|
      format.html { redirect_to news_index_url, notice: 'FAQ entry was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_news
      @news = News.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def news_params
      params.require(:news).permit(:title, :content)
    end
end