blakeyoder
blakeyoder

Reputation: 157

Multiple form inputs for the same field

I have a Rails model called request_form. In the form I have multiple boxes that can be selected, similar to the "What can we craft for you section" in the following site http://mostlyserious.io/get-started/

I have a field called number_of_guests that can be a handful of values depending on which section is clicked. I plan on using javascript to grab the value of the clicked element and assigning it to the request_no_of_guest param. However, in the form I have that same field rendered 5 times to allow for each selection. What is the best way about this? Is there a better way to handle this? I thought about creating a controller method that loops through each instance of that request_no_of_guests param and determining which instance is populated and then sending that up.

Is this the best way to handle this case?

Upvotes: 1

Views: 1085

Answers (1)

svelandiag
svelandiag

Reputation: 4320

Well as you did not provide any useful detail I will answer as I understood the question.

Let’s have a quick look at what this might look like. To do so, we’ll imagine a demo app into which you can enter the name of a professor and select their various areas of expertise.

Professor has a field expertise which is String.

The form can be as follows:

<%= label_tag 'expertise_physics', 'Physics' %>
<%= check_box_tag 'professor[expertise][]', 'Physics', checked('Physics'), id: 'expertise_physics' %>

<%= label_tag 'expertise_maths', 'Maths' %>
<%= check_box_tag 'professor[expertise][]', 'Maths', checked('Maths'), id: 'expertise_maths' %>

alter app/controllers/professors_controller.rb

from

params.require(:professor).permit(:name, :expertise)

to

params.require(:professor).permit(:name, expertise:[])

Then in app/models/professor.rb

before_save do
  self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("expertise")
end

and in /app/helpers/professors_helper.rb

def checked(area)
  @professor.expertise.nil? ? false : @professor.expertise.match(area)
end

This way you can grab the different values selected in the form into the expertise attribute, however this is not recommended if you are planning to query the selected options. The right way would be create a new model called Expertise and then create the relationship professor has_many expertises.

But if you are looking for something simple, then use the above code.

Upvotes: 3

Related Questions