0

I'm new to rails. What I'm trying to do is to design an order system. It lists a bunch of items and each item is followed by a select box so that people can choose the number that they want to order. My question is how to pass this count[] array and the corresponding item id from view to controller using button_to. Thank you for any suggestions.

  <% @items.each do |item| %>
    <li>
      <%= link_to item.name, item %>
      <%= select_tag 'count[]', options_for_select([0,1,2,3,4,5])%>
    </li>
  <% end %>
  <%= button_to 'Place Order', orders_confirm_path, method: :post, params: { ??? } %>

2 Answers 2

1

You use the tag multi-select.

example in your view. For can select multi with ctrl + click at item:

<%= form_tag orders_confirm_path, method: :post %>
<label>select more than one with ctrl + click at item</label>
<p><%= select_tag :items, Item.all.collect {|item| [item.name, tem.id]}, {prompt: "Select item"}, multiple: true %></p>

<p><%= button_to 'Place Order'%></p>

and your controller you can receive the parameters in this way:

def create @order = Order.new(params[:items]) if @order.save code ... else code ... end end

Sign up to request clarification or add additional context in comments.

Comments

0

You can this using form like below

<%= form_tag orders_confirm_path, method: :post do %>
    <% @items.each do |item| %>
        <%= hidden_field_tag :item_id, value: item.id %>
        <li>
          <%= link_to item.name, item %>
          <%= select_tag 'count[]', options_for_select([0,1,2,3,4,5])%>
        </li>
    <% end %>
    <%= button_to 'Place Order' %>
<% end %>

Now you can find on controller params[:count] params[:item_id]

Hope to help

2 Comments

Thank you very much! Is it possible to also keep the item id information with the count and pass them back to controller?
Got it. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.