ruby-on-rails - 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
解决方案
您可以使用一些助手来避免视图中的所有逻辑。一个例子:
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" %>
推荐阅读
- python - 将整数保存到文件并检索它
- javascript - Angular2:为什么'else'没有在订阅功能中执行?
- android - Galaxy Samsung s6 在打开我的应用程序时冻结,为什么?
- javascript - Immutable.js 有条件地更新 Map
- asp.net-core - 如何在没有 ASP.NET 身份的情况下使用授权
- java - 如何修复“在类路径资源中定义名称为 'entityManagerFactory' 的 bean 创建错误”
- c# - 如何知道是什么导致我的操作遇到多个线程?
- javascript - React-Leaflet:无效的 LatLng 对象
- java - 无法在 Grails 2.4.4 项目中实例化 OpenCV-4.0.1 CascadeClassifier
- sql - 如何使用 SQL 从汇总结果中计算每日平均值?