首页 > 解决方案 > Rails 5:如果 check_box 等于 true,则为 select 添加选项

问题描述

当提供商选择提供集合时,我试图在 show.html.erb 中显示不同的选项供用户选择。

问题是供应商有多种选择,1瓶、3瓶、6瓶和12瓶。

我的 _form.html.erb 摘要:

<% if @wine.is_1 == true %>
     <%= f.select :bottles, [["1 bottle", "1"]], id: "bottle", prompt: "Select...", class:"form-control" %>
    <% end %>

<% if @wine.is_3 == true %>
     <%= f.select :bottles, [["3 bottles", "3"]], id: "bottle", prompt: "Select...", class:"form-control" %>
    <% end %>

<% if @wine.is_6 == true %>
         <%= f.select :bottles, [["6 bottles", "6"]], id: "bottle", prompt: "Select...", class:"form-control" %>
        <% end %>

有没有使用 Reservations Controller 使代码最小化的替代方法?我将如何获得要支付的总金额?

预订控制器

class ReservationsController < ApplicationController
  before_action :authenticate_user!
def create
  wine = Wine.find(params[:wine_id])

  if current_user == wine.user
    flash[:alert] = "You cannot book your own wine!"
  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] = "Booked Successfully!"
end
  redirect_to wine

end

标签: ruby-on-railsruby-on-rails-5

解决方案


您可以使用一些助手来避免视图中的所有逻辑。一个例子:

module ApplicationHelper
  def wine_quantity(wine)
    case 
    when wine.is_1 then [["1 bottle", "1"]]
    when wine.is_3 then [["3 bottles", "3"]]
    when wine.is_6 then [["6 bottles", "6"]]
    when wine.is_12 then [["12 bottles", "12"]]
    else
    end
  end  
end

在您的_form.html.erb情况下,它可以简化为:

<%= f.select :bottles, wine_quantity(@wine), id: "bottle", prompt: "Select...", class:"form-control" %>

推荐阅读