class SalesController < ApplicationController
  def index
    @sales = Sale.all
  end

  def new
    @customers = Customer.all
    @products = Product.in_stock
  end

  def create
    sale = Sale.create(sale_params.except(:products_ids))

    redirect_to sales_index_path
  end

  def show
  end

  def edit
  end

  def delete
  end

  private

  def sale_params
    params.require(:sale).permit!
  end
end

class SalesController < ApplicationController
  def index
    @sales = Sale.all
  end

  def new
    @customers = Customer.all
    @products = Product.in_stock
  end

  def create
    sale = Sale.new(sale_params.except(:products_ids))
    if sale.valid?
      products_ids = sale_params[:products_ids].reject(&:blank?)
      Product.where(id: products_ids).each do |product|
        product.sale = sale
        product.sold!
        product.save
      end
      sale.save
    end

    redirect_to sales_index_path
  end

  def show
  end

  def edit
  end

  def delete
  end

  private

  def sale_params
    params.require(:sale).permit!
  end
end

Revert "remove logic which should not be in the controller"
Revert "remove logic which should not be in the controller"

This reverts commit f7014e403f99a2308d68ea60772176d6093ea2aa.
