Рельсы 5: Получить полное количество заказов - PullRequest
0 голосов
/ 26 октября 2018

Я хочу отобразить все заказы и общую сумму, заработанную для пользователя в представлении бронирования.

Я пробовал Reservation.count (: все), но, похоже, это не работает. Есть ли способ подсчета заказов от всех пользователей?

Вот мой текущий контроллер бронирования без каких-либо изменений:

class ReservationsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_reservation, only: [:approve, :decline]

  def create
    wine = Wine.find(params[:wine_id])

    if current_user == wine.user
      flash[:alert] = "Du kannst nicht deinen eigenen Wein kaufen!"
    else

    start_date = Date.parse(reservation_params[:start_date])

    @reservation = current_user.reservations.build(reservation_params)
    @reservation.wine = wine
    @reservation.price = wine.price
    @reservation.total = wine.price * @reservation.bottle
    # @reservation.save

  if @reservation.save
    if wine.Reservieren?
      flash[:notice] = "Anfrage versendet!"
  else
    @reservation.Bearbeitung!
    flash[:notice] = "Eroflgreich bestellt!"
  end
else
    flash[:alert] = "Can't make a reservation!"
  end

  end
    redirect_to wine
  end

  def your_orders
    @orders = current_user.reservations.order(start_date: :asc)
  end

  def your_reservations
    @wines = current_user.wines
      redirect_to root_path unless current_user.admin == true
  end

  def your_upcoming_reservations
    @wines = current_user.wines
      redirect_to root_path unless current_user.admin == true
  end


  def approve
    @reservation.Versendet!
    redirect_to your_reservations_path
    redirect_to root_path unless current_user.admin == true
  end

  def decline
    @reservation.Abgelehnt!
    redirect_to your_reservations_path
    redirect_to root_path unless current_user.admin == true
  end

  # Each Order Details
  def order_details
    @orders = current_user.reservations.order(start_date: :asc)
  end

  private

  def set_reservation
    @reservation = Reservation.find(params[:id])
  end

  def reservation_params
    params.require(:reservation).permit(:start_date, :bottle)
  end
end

А это мой текущий взгляд:

<div class="container-small">
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading">
        Alle Bestellungen
      </div>
      <div class="panel-body">
        <% @wines.each do |wine| %>
          <% wine.reservations.each do |reservation| %>
            <div class="row">
              <div class="col-md-3">
                Erwartet am<br/>
                <%= reservation.start_date.strftime('%v') %>
              </div>
              <div class="col-md-2">
                <p><%= reservation.status %></p>
                <div class="form-inline">
                  <% if reservation.Bearbeitung? %>
                    <%= link_to approve_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-up fa-lg"></i> <% end %> |
                    <%= link_to decline_reservation_path(reservation), method: :post do %> <i class="fa fa-thumbs-down fa-lg"></i> <% end %>
                  <% end %>
                </div>
              </div>
              <div class="col-md-4">
                <%= reservation.bottle %>x
                <%= link_to reservation.wine.wine_name, wine_path(reservation.wine) %><br/>
                Gesamt: <%= reservation.total %>€<br/>
              </div>
              <div class="col-md-3 pull-right">
                Lieferung an<br/><br/>
                <span>
                  <%= link_to user_path(reservation.user) do %>
                    <%= reservation.user.fullname %><br/>
                  <% end %>
                  <%= reservation.user.location %>
                </span>
              </div>
            </div>
            <hr/>
          <% end %>
        <% end %>
      </div>
    </div>
  </div>
</div>
</div>

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

Альтернативный синтаксис для явного указания, что вы подсчитываете все резервирования:

@count = Reservation.all.count

Лично мне нравится быть настолько очевидным, насколько это возможно, в отношении того, что я ожидаю от запроса.Например, что если в будущем вы захотите рассчитывать только резервирование, которое не было отменено, или, возможно, рассчитывать только резервирование за определенный месяц?

Остальная часть ответа Р. Сьерра находится на стадии.

0 голосов
/ 26 октября 2018

В контроллере вы должны вызвать:

@count = Reservation.count()
@total = Reservation.sum(:total)

И затем в представлении:

Reservations Count: <%= @count %>
Reservations Total: $ <%= @total %>

Документация Ruby On Rails API для count и сумма

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...