0
votes

I'm implementing select2 tagging with a has_many through relationship. My implementation has 2 different scenarios.

  1. The select menu allows multiple (tagging) but does not allow on the fly input into the select menu.
  2. Same as above but uses ajax to allow the user to enter new select values on the fly.

Scenario 1 works well for tagging. Scenario 2 seems to work (can perform tagging) but does not save the values. My problem seems to come down to my my input elements for the scenarios.

Scenario 1 uses:

<%= f.association :repairers, label_method: :rep_name, value_method: :id, include_blank: true, label: 'Repairer'%>

and when the form is submitted gives params similar to:

"repairer_ids"=>["", "1132", "1131"]

Scenario 2 uses:

<%= f.hidden_field :repair_type_id, :class => "required on-the-fly-select select"%>

and uses a lot of js code to implement on the fly input for the select menu. When the form is submitted the data will look like:

"repair_type_id"=>"5688,5690"

So with scenario 2 the ids are not submitted as an array. I have tried changing the select to:

<%= hidden_field_tag("repair_item[repair_type_ids][]", "", :id => "repair_item_repair_type_ids", :class => "required on-the-fly-select select") %>

but then the relevant param is submitted incorrectly and doesn't save:

"repair_type_ids"=>["5688,5690"]

Is it possible to get the params from Scenario 2 to submit in the format that Rails made the params in Scenario 1?

1
why can't use split method of ruby to convert that data string into array and store into DB - anusha

1 Answers

0
votes

Try String#split

repair_type_id = "5688,5690"
repair_type_id.split(',')
=> ["5688", "5690"]

It's Better to use this split method in controller while saving the data on particular attribute for this instead of on hidden_tag.

Edit:

If you want to convert string in plural then use pluralize same as for singularize

2.0.0-p481 :010 > 'cat'.pluralize 
 => "cats" 
2.0.0-p481 :011 > 'dogs'.singularize
 => "dog"