Populating Select Box with Hash Array in rails - ruby-on-rails

Anyway I've created a Hash Array :
#example= ['A' => '1', 'B' => '2']
or Array
#example=[1,2]
here you've got the key (being the english name) and the value (the
generic equivalent).
what I want to do is make a drop-down single-selection box use these
key/value properties to render it correctly,
<%= f.collection_select #example %>
...this doesn't work but what i'd like is generate the form code...
#from HASH
<select >
<option value="1">A</option>
<option value="2">B</option>
</select>
or
#from array
<select>
<option>1</option>
<option>2</option>
</select>
Any help really appreciated.

For:
#example = [["A", 1, {:class=>"bold"}], ["B", 2], ["C", 3]] # {:class=> "bold"} is optional, use only if you need html class for option tag.
Try:
<%= form_for #whatever do |f|%>
# some code here..
<%= f.select :example, options_for_select(#example) %>
# rest of the code..
<% end %>
Or you can use:
<%= form_for #whatever do |f|%>
# some code here..
<%= f.select :example, #example %> # I am guessing that maybe you can not pass hash here for option tag.
# rest of the code..
<% end %>
Without form_for:
<%= select_tag :example, #example %>
# or
<%= select_tag :example, options_for_select(#example)%>

Related

how to get selected value from a dropdown on click in ruby on rails?

I am new to ruby on rails please help me with this simple code :
I need to print
'HI' if option 1 is selected
'BONJOUR' if option 2,
'HOLA' if option 3,
'NAMASTE' if option 4.
on selecting a value on the dropdown and click the button,
<%= form_for :person do |f| %>
<%= f.select :desired_attribute, ['option1','option2','option3','option4']%>
<%= button_to "Show Text" , :onclick => "show_back(), return false" %>
<% end %>
involve your server.
view. Add remote: true to your form. And handle ajax request in controller. more about ajax in rails
<%= form_for :person, remote: true do |f| %>
<%= f.select :desired_attribute, options_for_select([ ['option1', '1'],['option2', '2'],['option3', '3'],['option4', '4']]) %>
<%= button_to "Show Text" , :onclick => "show_back(), return false" %>
<% end %>
in your controller
class PersonsController
MY_HASH = { '1': 'HI', '2': 'BONJOUR', '3': 'HOLA', '4': 'NAMASTE' }
def name_of_action
respond_to do |format|
format.js { render 'your_partial_name', name: MY_HASH[params[:person][:desired_attribute]] }
end
end
your_partial_name.js.erb
alert("<%= name %>");
Instead of MY_HASH it's better to use I18n to handle language issues. more about I18n
Use this syntax:
<%= f.select :point1, options_for_select([ ['option1', 'HI'],['option2', 'BONJOUR'],['option3', 'HOLA'],['option4', 'NAMASTE']]) %>
you will dropdown like this:
<select id="point1">
<option value="HI">option1</option>
<option value="BONJOUR">option2</option>
<option value="HOLA">option3</option>
<option value="NAMASTE">option4</option>
</select>
Dropdown option map with its value then you will get the value.

How to add selected attribute in f.select helper in rails?

i have written the f.select helper for this code
<select>
<option>abc</option>
<option>def</option>
<option selected>ghi</option>
</select>
<%= f.select(:xFields, ['abc', 'def', 'ghi]) %>
How do i make option 'ghi' selected as default?
edit
try this:
<%= f.select options_for_select(:xFields, ['abc', 'def', 'ghi'], 'ghi') %>
the following should work
<%= f.select(:xFields, [['ghi'], 'abc', 'def']) %>
based on Rails 3: f.select - options_for_select
This is working
<%= f.select(:xFields, options_for_select( ['abc', 'def', 'ghi'], 'ghi')) %>

Rails select options tag - generating options from associations

I have a view that allows the user to add list_items to one of their shopping_lists. I want the options for select to be the names of their lists, but I need those names mapped to respective list_id in order to have the correct associations. Here's my current select tag:
<tr>
<% item.inventory_items.each do |product| %>
<td>
<%= form_tag("/list_items", method: "post") do %>
<%= hidden_field_tag(:item_id, item.id) %>
<%= hidden_field_tag(:inventory_item_id, product.id) %>
<%= select_tag(:shopping_list_id, options_for_select(current_user.shopping_lists)) %>
<%= submit_tag("$#{product.price}", class: "btn btn-primary") %>
<% end %>
</td>
<% end %>
</tr>
How can I display the names of a user's shopping_lists as the options, but return the relative shopping_list_id as the value for that option?
ShoppingList belongs_to :user
User has_many :shopping_lists
Currently my select tag renders a dropdown selection of a user's shopping lists, but the options are listed in the form, '#. Clicking the submit button doesn't actually add the the item to the list either.
Thanks in advance!
As you can see in Rails Api documentation:
options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
# => <option value="$">Dollar</option>
# => <option value="DKK">Kroner</option>
options_for_select receives an Array of Arrays. Inner Arrays are only two elements: ["name", "value"].
You can create a class method in your ShoppingList model as follows:
def self.options_for_list(shopping_lists)
shopping_lists.map do |sl|
[ sl.name, sl.id ]
end
end
It returns the Array you need, then:
<%= select_tag :shopping_list_id, options_for_select(ShoppingList.options_for_list(current_user.shopping_lists)) %>
EDIT:
Or use a helper method:
def shopping_list_select_tag(shopping_lists, options = {})
select_options = shopping_lists.map do |sl|
[ sl.name, sl.id ]
end
select_tag :shopping_list_id, options_for_select(select_options), options
end
Then,
<%= shopping_list_select_tag current_user.shopping_lists %>

Is there a way to set a distinct ID and name for a text_field in Rails 2?

I've got a Rails 2 site I'm trying to add a form handler to, but I'm running into problems converting the html form fields into form handler fields.
The form code begins with:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
I keep getting errors when I try things like
<%= text_field :newsavedmap, :html=>{ :value => 'New Map', :name=>'newsavedmapname', :id=> 'savedmap_name', :size => '30' } %>
Error:
ActionView::TemplateError (wrong number of arguments (1 for 2)) on line #284 of app/views/layouts/maptry.html.erb:
Here are the fields. How can I convert these to form handler fields in Rails 2?
<input id="savemap_name" name="newsavedmapname" size="30" type="text" value="New Map"></p>
<select id="startdrop" name="startthere">
<OPTIONS HERE>
</select>
<select multiple id="waypoints" class="mobile-waypoints-remove" name="waypointsselected[]">
<OPTIONS HERE>
</select>
Thanks for any help you can provide!
Edit 1 Error Code for the Text_Field
Using Bigxiang's approach, I get
Processing NewsavedmapsController#create (for IP at Date Time) [POST]
Parameters: {"endhere"=>"", "endthere"=>"SAMPLE ADDRESS 1", "newsavedmap"=>{"newsavedmapname"=>"test Map"}, "startthere"=>"SAMPLE ADDRESS 2", "starthere"=>"", "optimize"=>"on"}
ActiveRecord::UnknownAttributeError (unknown attribute: newsavedmapname)
The line with "newsavedmap"=>{"newsavedmapname"=>"test Map"} should just read
"newsavedmapname"=>"test Map"
How can I do this? My controller starts with:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :newsavedmapname :id=>"savemap_name", :size=>30, :value=>"New Map"%>
<%= f.select :startthere, YOUR_COLLECTIONS, {}, {:id=>"startdrop"}%>
<%= f.select :waypointsselected, YOUR_COLLECTIONS, {}, {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
make sure YOUR_COLLECTIONS should be an array like ['a', 'b', 'c'] or [['name1', id1],['name2', id2],['name3', id3]].
If you persist the parameter is "newsavedmapname"=>"test Map", try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= text_field_tag :newsavedmapname, "New Map", :id=>"savemap_name", :size=>30%>
<%= select_tag :startthere, options_for_select(YOUR_COLLECTIONS), {:id=>"startdrop"}%>
<%= select_tag :waypointsselected, options_for_select(YOUR_COLLECTIONS), {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
But I don't understand why not use parameter's name as same as the column's name. For example, I see your newsavedmap model has a column named "name". you can use it directly
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :name , :value=>"New Map" %>
<% end %>
in your controller , you can delete line #newsavedmap.name = params[:newsavedmapname]
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
if #newsavedmap.save
#######
end
end

RoR 3.2.8: Is there an HTML5 combobox helper?

Right now, I'm using the form_for.select and options_for_select rails helpers to create a select box with the data from the model. However, what I really need is a combobox like the one introduced with HTML5:
<input type=text list=browsers >
<datalist id=browsers >
<option> Google
<option> IE9
</datalist>
Is there a rails helper for creating such elements?
No, but it's quite easy to setup your own form builder helper method to achieve such a result, a simple example would be:
app/form_builders/combobox_form_builder.rb
class ComboboxFormBuilder < ActionView::Helpers::FormBuilder
include ActionView::Context # for nested content_tag
include ActionView::Helpers::FormTagHelper #for sanitize_to_id method access
def combobox_tag(name, options, opts= {})
#template.content_tag(:input, :name => name, :id => sanitize_to_id(name), :type => "text", :list => opts[:list_id]) do
content_tag(:datalist, :id => opts[:list_id]) {options}
end
end
end
After restarting your server you can implement your new combobox using the form builder by specifying a builder argument in your form_for call:
<%= form_for #foo, builder: ComboboxFormBuilder do |f| %>
<%= f.combobox_tag(:browser, options_for_select(["Firefox", "Chrome", "IE9"]), :list_id => "list")%>
<% end %>
Output HTML:
<input type="text" name="browser" list="list" id="browser">
<datalist id="list">
<option value="Firefox">Firefox</option>
<option value="Chrome">Chrome</option>
<option value="IE9">IE9</option>
</datalist>
Keep in mind that both IE & Safari do not offer support for the HTML5 Datalist.
<%= form_for #person do |f| %>
<%= f.label :first_name, "First Name" %>:
<%= f.text_field :first_name, list: 'first-name' %>
<datalist id="first-name">
<% Person.all.each do |person| %>
<option value="<%= person.first_name %>"></option>
<% end %>
</datalist>
<%= f.submit %>
<% end %>
You may also want to do distinct:
<% Person.select(:first_name).distinct.each do |person| %>
Just example from my code:
= form_tag controller:'beer', action: 'create' do
= text_field :beer, :name, list: 'beer-name'
%datalist#beer-name
- Beer.all.each do |beer|
%option{value: beer.name}

Resources