【问题标题】:Validations in form_tagform_tag 中的验证
【发布时间】:2019-01-30 14:47:58
【问题描述】:

在我的在线商店中,我想在将产品添加到购物车之前进行验证

我的 order_item 表格在产品展示中

我想强制用户选择尺寸,如果没有选择尺寸,则显示错误消息

尺寸是产品的嵌套属性

我应该怎么写?

<%= form_tag clients_order_items_path, input_html: {id: "orderform"} do %>
    <%= hidden_field_tag :product_id, @product.id %>
    <%= hidden_field_tag :user_id, @token %>
    <%= hidden_field_tag :quantity, 1 %>            
    <%= select_tag :size_id, options_from_collection_for_select(@product.sizes.where('quantity >=1'), :id, :size_name), prompt: "Your Size", class: 'form-control custom-select'%>  
<%= submit_tag "Add to cart", class: "btn-main", id: "add_to_cart" %>

这里是带有 create 方法的 OrderItemsController:

 def create
    @item = current_cart
    @size = Size.find(params[:size_id])

    if @size.quantity >= params[:quantity].to_i

      current_cart.add_item(
        product_id: params[:product_id],
        quantity: params[:quantity],
        size_id: params[:size_id],
      )

      redirect_to clients_cart_path
    else
      redirect_to clients_product_path(Product.find(params[:product_id]))

    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    强制用户选择一种尺寸:

    <%= select_tag :size_id, options_from_collection_for_select(@product.sizes.where('quantity >=1'), :id, :size_name), {include_blank: 'Your Size'}, required: true, class: 'form-control custom-select'%>
    

    这将使select 成为必需,如果未选择大小,则会出现浏览器自定义消息。

    如果你想自定义消息,并显示在发出请求之前,考虑使用JS,我推荐https://jqueryvalidation.org/

    OBS:这是一个很好的做法,不要对您的视图执行数据库查询,考虑在您的控制器中创建@product.sizes.where('quantity &gt;=1'),例如:

    # Inside your controller
    def show
        ...
        @product_size_options = @product.sizes.where('quantity >=1')
        ...
    end
    

    还有你的select_tag

    <%= select_tag :size_id, options_from_collection_for_select(@product_size_options, :id, :size_name), {include_blank: 'Your Size'}, required: true, class: 'form-control custom-select'%>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多