johan
johan

Reputation: 721

Validations in form_tag

In my online shop I want to have validation before adding a product to the cart

my order_item form is in the product show

I want to force the user to select a size, and display an error message if no size chosen ?

Size is a nested attributes of products

How I am supposed to write it?

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

here is the OrderItemsController with the create method:

 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

Upvotes: 2

Views: 39

Answers (1)

Dimitrius Lachi
Dimitrius Lachi

Reputation: 1287

To force user to select one size:

<%= 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'%>

This will make the select required, and the browser custom message will appears if size not selected.

If you want to customize the message, and shows before the request are made, consider use JS, i recommends https://jqueryvalidation.org/

OBS: Its a good pratice, don't perform databases queries on your view, consider to make @product.sizes.where('quantity >=1') in your controller like:

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

and your 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'%>

Upvotes: 1

Related Questions