Home > OS >  How to pass in item Id to text field tag from datalist
How to pass in item Id to text field tag from datalist

Time:04-05

Currently I learning about Ruby on Rails. So I try to make 1 simple app, but I facing some problem.

I want to pass the item id from select tag datalist to text field tag in rails. But I want to show item name and item code in my select tag datalist. So now I not sure to pass the item id to the text field tag. I have attach my code down below.

expected parameter to backend

["1", "2"]

now it sending parameter to backend

["CM", "NM"]

Expected View

So this the code for text field tag and select tag

<div >
  <%= f.label :item, class: 'required'%>
   <% items = Item.where(company_id: current_user.company.id)%>
   <%= text_field_tag "[supplier_item][item_ids][]", nil, {list: 'browser-item'} %>
     <datalist id="browser-item" >
        <%= select_tag "[supplier_item][item_select][]", options_for_select(items.collect{ |item| [item.name, item.item_code]}), {class: "form-control"} %>
      </datalist>
 </div>

CodePudding user response:

I am not sure if the expected view you have added in the question is your current view or not as the code would not render that I think.

As you want to display both item name and item_code and pass the item id to backend you can use string concatenation:

<%= select_tag "[supplier_item][item_select][]", options_for_select(items.collect{ |item| ["#{item.name} - #{item.item_code}", item.id]}), {class: "form-control"} %>

The option tag has an attribute value which is the value sent to the backend and when creating a select_tag using options_for_select you pass an array of array values something like this:

[['A', 1], ['B', 2], ['C', 3]]

This would be rendered as:

<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>

i.e., the first value as the label and the second as the actual value of the option tag which would be sent to the backend. This is the reason you are getting the item_code on the backend right now instead of id.

Update: As you are using datalist the label doesn't matter it always displays the value, there is a good discussion here for your case if you wish to have a different display value. An alternative is to use a select tag if that does the job for you or there are some good solutions in the above link.

  • Related