Rails 5:如果check_box等于true,则添加用于选择的选项

时间:2018-10-22 10:08:35

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

当提供商选择提供广告集时,我试图显示不同的选项供用户在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

1 个答案:

答案 0 :(得分:0)

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

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" %>