У меня есть форма в приложении Rails, которая публикует, но не сохраняет входные данные.
У поставщика услуг есть возможность определить различные наборы вина, которые он предлагает, например, 1,3,6, 12 и более общая информация, которая отображается в show.html.erb (wine_controller).
UPDATE
В пределах show.html.erb отображается _form.html.erb,который использует reservations_controller.
Логика заключается в том, что у вина может быть много резервирований.
В настоящее время бутылки сохраняются в БД, но общая сумма не сохраняется в БД, поскольку контроллер резервирования выдает ошибку NoMethodErrorпоскольку бутылки - это неопределенная локальная переменная или метод.
Контроллер вин
class WinesController < ApplicationController
before_action :set_wine, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]
before_action :is_authorised, only: [:details, :pricing, :description, :photo_upload, :more_details, :sets, :location, :update]
def index
@wines = current_user.wines
end
def new
@wine = current_user.wines.build
end
def create
@wine = current_user.wines.build(wine_params)
if @wine.save
redirect_to details_wine_path(@wine), notice: "Saved..."
else
flash[:alert] = "Something went wrong..."
render :new
end
end
def show
@photos = @wine.photos
@guest_reviews = @wine.guest_reviews
end
def details
end
def pricing
end
def description
end
def photo_upload
@photos = @wine.photos
end
def more_details
end
def sets
end
def location
end
def update
new_params = wine_params
new_params = wine_params.merge(active: true) if is_ready_wine
if @wine.update(wine_params)
flash[:notice] = "Saved..."
else
flash[:alert] = "Something went wrong..."
end
redirect_back(fallback_location: request.referer)
end
def preload
today = Date.today
# Reservations greater than today (upcoming reservations)
reservations = @wine.reservations.where("start_date >= ?", today)
render json: reservations
end
private
def set_wine
@wine = Wine.find(params[:id])
end
# Authorize user (current_user == ID 1)
def is_authorised
redirect_to root_path, alert: "You don't have permission" unless current_user.id == @wine.user_id
end
def is_ready_wine
!@wine.active && !@wine.price.blank? && !@wine.base_price.blank? && !@wine.wine_name.blank? && !@wine.summary.blank? && !@wine.photos.blank? && !@wine.alcohol.blank? && !@wine.filling.blank? && !@wine.in_stock.blank? && !@wine.address.blank?
end
def wine_params
params.require(:wine).permit(:wine_type, :wine_color, :wine_art, :alcohol, :wine_name, :summary, :address, :is_1, :is_3, :is_6, :is_12, :filling, :base_price, :price, :in_stock, :year, :active)
end
end
Reservation.rb
class Reservation < ApplicationRecord
before_save :update_financials
belongs_to :user
belongs_to :wine
def update_financials
total = wine.price * bottles if wine.present? && bottles.present?
price = wine.price if wine.present?
end
end
Функция My Helper для _form.html.erb
def wine_quantity(wine)
case
when wine.is_1 && wine.is_3 && wine.is_6 && wine.is_12 then [["1 Flasche", 1], ["3 Flaschen", 3], ["6 Flaschen", 6], ["12 Flaschen", 12]]
when wine.is_1 && wine.is_3 && wine.is_6 then [["1 Flasche", 1], ["3 Flaschen", 3], ["6 Flaschen", 6]]
when wine.is_1 && wine.is_3 && wine.is_12 then [["1 Flasche", 1], ["3 Flaschen", 3], ["12 Flaschen", 12]]
when wine.is_1 && wine.is_6 && wine.is_12 then [["1 Flasche", 1], ["6 Flaschen", 6], ["12 Flaschen", 12]]
when wine.is_1 && wine.is_12 then [["1 Flasche", 1], ["12 Flaschen", 12]]
when wine.is_1 && wine.is_6 then [["1 Flasche", 1], ["6 Flaschen", 6]]
when wine.is_1 && wine.is_3 then [["1 Flasche", 1], ["3 Flaschen", 3]]
else
end
end
Если поставщик услуг предлагает 6 и 12 бутылок, в форме отображаются только 6 и 12 бутылок. Html.erb
My _form.html.erb:
<div class="panel-body">
<%= form_for([@wine, @wine.reservations.new]) do |f| %>
<div class="panel-body">
<div class="col-md-12">
<label>Lieferdatum</label>
<%= f.text_field :start_date, readonly: true, placeholder: "Lieferdatum", class: "form-control datepicker" %>
</div>
<!-- BUY SET? -->
<div class="col-md-12 select" style="margin-top:10px">
<div class="form-group">
<label>Anzahl an Flaschen</label>
<%= f.select :bottles, wine_quantity(@wine), {}, id: "bottles", prompt: "Auswählen...", class: "form-control" %>
</div>
</div>
</div>
<div id="preview" style="display:none">
<table class="reservation-table">
<tbody>
<tr>
<td>Preis pro Flasche</td>
<td class="text-right"><%= @wine.price %>€</td>
</tr>
<tr>
<td>Anzahl Flaschen</td>
<td class="text-right">x <span id="reservation_bottles"></span></td>
</tr>
<tr>
<td class="total">Gesamt</td>
<td class="text-right"><span id="reservation_total"></span>€</td>
</tr>
</tbody>
</table>
</div>
<br/>
<%= f.submit "Bestellen", id: "btn_book", class: "btn btn-normal btn-block", disabled: true %>
<% end %>
</div>
</div>
<script>
$(function() {
$.ajax({
url: '<%= preload_wine_path(wine_id: @wine.id) %>',
dataTyp: 'json',
success: function(data) {
var bottles = document.getElementById("bottles").value;
var total = bottles * <%= @wine.price %>
$('#reservation_bottles').text(bottles);
$('#reservation_total').text(total.toFixed(2));
$('#reservation_start_date').datepicker({
dateFormat: 'dd-mm-yy',
minDate: 2,
maxDate: '5d',
beforeShowDay: $.datepicker.noWeekends,
onSelect: function(selected) {
$('#preview').show();
$('#btn_book').attr('disabled', false);
$('#bottles').on('click', function() {
var bottles = $(this).val();
var total = bottles * <%= @wine.price %>
$('#reservation_bottles').text(bottles);
$('#reservation_total').text(total.toFixed(2));
});
}
});
}
});
});
</script>
My Reservations Controller:
class ReservationsController < ApplicationController
before_action :authenticate_user!
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 * bottles
@reservation.save
flash[:notice] = "Erfolgreich Bestellt!"
end
redirect_to wine
end
def your_orders
@orders = current_user.reservations.order(start_date: :asc)
@today = Date.today
end
def your_reservations
@wines = current_user.wines
end
# Each Order Details
def order_details
@orders = current_user.reservations.order(start_date: :asc)
end
private
def reservation_params
params.require(:reservation).permit(:start_date)
end
end
Когда я пытаюсь внедрить: bottle в reservations_controller.rb, я получаю NoMethodError ... Я думаю, что я анализирую входные данные из формы.Неверный html.erb к контроллеру резервирования.
Вот запрос:
{"utf8"=>"✓",
"authenticity_token"=>"3xgM8kSLwa+8JafBZYMoX+BA2XgelWY5bY7yENMrtqAxXCrBb6IabNFa72BG0H6jYnszkzZ/oilOLbka2mmVUA==",
"reservation"=>{"start_date"=>"26-10-2018", "bottles"=>"3"},
"commit"=>"Bestellen",
"wine_id"=>"3"}