class Admins::DisciplinesController < Admins::BaseController

  def index
    @disciplines = Discipline.all
  end

  def create
    name = params[:name].to_s.strip
    return render_error('名称重复') if Discipline.where(name: name).exists?
    Discipline.create!(name: name)
    render_ok
  end

  def edit
    @discipline = current_discipline
  end

  def update
    if params[:discipline] && params[:discipline][:name].present?
      name = params[:discipline][:name].to_s.strip
      current_discipline.update_attributes!(name: name)
    else
      ActiveRecord::Base.transaction do
        current_discipline.update_attributes!(setting_params)
        current_discipline.sub_disciplines.each do |sub|
          sub.tag_disciplines.each do |tag|
            tag.update_attributes!(setting_params)
          end
          sub.update_attributes!(setting_params)
        end
      end
    end
    @disciplines = Discipline.all
  end

  def destroy
    @discipline_id = params[:id]
    current_discipline.destroy!
  end

  private
  def current_discipline
    @_current_discipline = Discipline.find params[:id]
  end

  def setting_params
    params.permit(:shixun, :subject, :question)
  end
end