Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails collection_select custom name attribute

I have the following collection select which acts as a filter in a Rails app.

<%= form_tag( "/appointments", :method => "get", :id => "filter_form") do %>
   <%= collection_select :doctor, :id, @doctors, :id, :full_name, {:include_blank => 'All'} %>
<% end %>

This always generates a name attribute of the select element like name="doctor[id]" which results in the browser to ?utf8=✓&doctor%5Bid%5D=1, which is not quite readable.

How can I change the name attribute to just name = "doctor" or basically just remove the brackets from it?

like image 808
interboy Avatar asked May 02 '13 02:05

interboy


People also ask

What is the difference between pluck vs select in rails?

In Rails, Pluck vs Select can be understood while active record querying. Pluck is used to get an array of particular attribute based on particular condition. Same can be obtained using select and then collect on a model. This tutorial will help you understand the difference between these ways of collecting specific attribute values.

How do I generate form elements in Ruby on rails?

Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in _tag such as text_field_tag, check_box_tag, etc., generate just a single <input> element.

What is cross-site request forgery protection in Ruby on rails?

This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form whose action is not “get” (provided that this security feature is enabled). You can read more about this in the Ruby On Rails Security Guide.


1 Answers

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

The collection_select method contains the parameters "options" and "html_options". "options" allow you to add specific information, like {:include_blank => 'All'}, but does not replace html attributes.

You have to add the name to the next hash, like this:

<%= form_tag( "/appointments", :method => "get", :id => "filter_form") do %>
   <%= collection_select :doctor, :id, @doctors, :id, :full_name, {:include_blank => 'All'}, {:name => 'doctor'} %>
<% end %>
like image 182
Ronnie Cheng Avatar answered Oct 01 '22 11:10

Ronnie Cheng