How to add 'select one...' to options_from_collection_for_select - ruby-on-rails

Below is my select-form that works properly.
When the user loads the page it shall show an initial ‘select one...’ with value null or ‘’.
I tried to add it to the Object but wasn’t able to and would be glad to get help!
Thanks a lot!
In my view:
= select_tag 'incident[fault_id]' , options_from_collection_for_select( Fault.all, :id, :label)
I use Rails 3.2 and HAML
Update:
By chance I found something really sweet:
include_blank: 'select one...'
or completely
= f.collection_select :fault_id, Fault.order(:label), :id, :label, include_blank: 'select one...'
In case one likes that too...
Reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

options_from_collection_for_select returns a string of option tags that have been compiled by iterating over the collection and assigning the result of a call to the value_method as the option value and the text_method as the option text.
So just prepend it with "select_one" option string without value:
= select_tag 'incident[fault_id]', content_tag(:option,'select one...',:value=>"")+options_from_collection_for_select( Fault.all, :id, :label)

:prompt is a property of select_tag not of options_from_collect_for_select so
select_tag("sales_rep[manufacturer_id]", options_from_collection_for_select(#manufacturers, "id", "name"), { :prompt => 'Select Manufacturer' })

You could try the following:
collection_select(:sales_rep, :manufacturer_id, #manufacturers, :id, :name, { :prompt => 'Select Manufacturer' })

Related

Getting value of an object in collection select

I have created drop down list for employees.
What I want?
I want to select full Name for each one of them.
Type of form:
I use simple_form.
I actually have:
= f.input :person_id, label: "Employee", collection: #employee, prompt: "Select employee"
Result(I know, that is reference):
Before I use collection_select, but simple_form doesn't support validation for this type of collection.
Code for collection_select. This type of drop down list displays properly full name.
= f.collection_select :person_id, #employee, :id, :fullName, {prompt: "Wybierz pracownika"}, {class: "form-control"}
Update:
fullName is a method in a person.rb model.
def fullName
"#{first_name} #{last_name}"
end
Object employee.
#employee = Person.where.not(type: "Client")
The easiest way to do this is :
= f.select :person_id, options_for_select(#employees.map{|e| [e.fullName, e.id]}), {:prompt=>"Wybierz pracownika", :required => true}
It will show full names as select options and will dispatch ids as values with form.
You follow this code like below:
<%= f.collection_select(:person_id, Model.all, :person_id, :fullName,{:prompt=>"Wybierz pracownika"}, {:class => 'form-control'}) %>
You will replace your model_name.
Or
= f.input :person_id, label: "Employee", collection: #employee.fullName, prompt: "Select employee"
I think will help you

Rails collection_select "selected" value is cancelled out by the default "prompt"

Couldn't find any reference to my problem in the API, so here goes:
<%= f.collection_select :category_id, #categories, :id,
:name, {prompt: true}, { selected: #selected_value } %>
My users arrive to the form from different links, and depending on the link, they get their categories pre-selected for them from the #categories set. Sometimes they come from a general page, so instead of a pre-selected option they see the default prompt.
Problem: with my current code prompt replaces the selected value.
Thanks for any advice!
So I went with placing a conditional inside my collection_select and now it works fine
<%= f.collection_select :category_id, #categories, :id, :name,
#selected_category ? {prompt: "Your text"} : {selected: #selected_category} %>

How to set a child attribute as collection_select value?

My form contains the following tag:
<%= f.collection_select :employee_id, #employees, :id, :value, :prompt => true %>
Employee looks like this:
employee
- attr1
- attr2
- user
- firstname
- lastname
My question: How to set the lastname of an employee as the value in the select field? I'm pretty sure it's possible, but I think I have some gaps in the syntax.
Why would you do that?
It's possible, with:
<%= f.collection_select :employee_id, #employees, :last_name, :text_method, :prompt => true %>
Where :text_method is method which called on #employees members will return text that you'd like to appear in dropdown.
You may be asking yourself why I have used <%= f.select %> this is FormOptionHelper on the Ruby on Rails Api this is very similar to collection_select however with that it returns and tags for the collection of values. Whereas select creates a series of contained option tags for provided object and method. So in saying this I believe you could have the following:
<%= f.select(:employee_id, Employee.all.collect { |emp| [emp.lastname, user.id] }
.sort{ |a, b| a[0] <=> b[0] }, {:prompt => "Select a Employee"}) %>
This selects all employees and sorts them in order of their last name.

How to use a table column in my select box on rails?

I'm trying to create a select box that takes data from my db. I'm having trouble setting this up. I tried this code:
<%= f.fields_for :unit do |u| %>
<%= u.label :name %>
<%= u.select :name, :class => "ingredient_unit", :prompt => "Please Select" %>
<% end %>
but I'm missing the part of the choices, I don't know how to pull them out of the database. I tried using collection_select, which worked, but then the class option wasn't working... collection_select went like this:
<%= u.collection_select :unit, Unit.all, :id, :name, :class => "ingredient_unit", :prompt => "Please Select" %>
I also don't understand what the first symbol means (:unit), it seems to be setting the html id and name, so that can be anything I want it to be?
You should look at the documentation for collection_select and select. But to answer your question, for the select part, you forgot to pass the list of options to choose from. You also need to swap the order for prompt and class since prompt is an option for the helper and class is an html option
<%= u.select :unit_id, Unit.all.map { |u| [u.name, u.id] }, { :prompt => "Please Select" }, { :class => "ingredient_unit" } %>
For the collection select
<%= u.collection_select :unit_id, Unit.all, :id, :name, { :prompt => "Please Select" }, { :class => "ingredient_unit" } %>
The first parameter passed to both helper is the column name where you want the selected answer to be saved. The 2 codes above just shows 2 different ways to generate the same select tag.
The first symbol tells it which field to populate with the id returned from the user selection.
Also, you should wrap your class section in {}
:unit refers to the model attribute that you're using for the select element. Yes, it will setup the name/id of the element (and name is the most important for the params hash).
To set a class in the collection_select, specify it as a hash as that helper takes it as an html_option.
<%= u.collection_select :unit, Unit.all, :id, :name, { :prompt => "Please Select" }, { :class => "ingredient_unit" } %>

Include blank for first item in select list in options_for_select tag

I tried :include_blank => true, but it didn't work.
<select>
<%= options_for_select Model.all.collect{|mt| [mt.name, mt.id]} %>
</select>
If I need to add it to the collection, how would you do that?
I think you want this format:
select("model_name", "model_id", Model.all.collect {|mt| [ mt.name, mt.id ] }, {:include_blank => 'name of your blank prompt'})
BTW: was assuming Modle was suppose to be Model. To use using collection_select:
collection_select(:model, :model_id, Model.all, :id, :name, :prompt => true)
I believe the :include_blank options only exist for select fields tied to a model.
Assuming you want to use a plain <select> tag instead of a <%= select(...) %> tied to a model, you can insert a blank entry at the front of your results:
<%= options_for_select Modle.all.collect{|mt| [mt.name, mt.id]}.insert(0, "") %>
Since you have tagged as select-tag you can use the option include_blank with select_tag.
From the documentation:
select_tag "people", options_from_collection_for_select(#people, "id", "name"), :include_blank => true
# => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
Or you can use options_for_select:
<%= select_tag column.name, options_for_select(Model.all.collect{|mt| [mt.name, mt.id]}), :include_blank => true %>
<%= options_for_select Model.all.collect{|x| [x.name,x.id]}.unshift(["",nil]) %>
= select_tag "some_value", options_for_select(Model.all.collect{ |x| [x.name, x.id]}.prepend([t('helpers.some_name'), nil]), :selected => params[:some_value])
If you want a slick solution you can use my gem rearmed_rails which has a feature in it that safely monkey patches options_for_select and options_for_collection_select
rails g rearmed_rails:setup
Open config/initializers/rearmed_rails.rb and change the following values to true
options_for_select_include_blank: true,
options_from_collection_for_select_include_blank: true
Now whenever you need a blank included simply do the following:
<%= options_for_select(Model.all.map{|x| [x.name,x.id]}, include_blank: true) %>
You can use the following monkey patch to add the include_blank argument to options_for_select
module OptionsForSelectIncludeBlankPatch
def options_for_select(container, selected = nil)
if selected.is_a?(Hash)
include_blank = selected[:include_blank] || selected['include_blank']
end
options = super
if include_blank
include_blank = '' if include_blank == true
if Rails::VERSION::MAJOR >= 5 && Rails::VERSION::MINOR >= 1
str = tag_builder.content_tag_string(:option, include_blank, {value: ''})
else
str = content_tag_string(:option, include_blank, {value: ''})
end
options.prepend(str)
end
options
end
end
ActiveSupport.on_load(:action_view) do
ActionView::Base.send(:include, RearmedRails::RailsHelpers)
end

Resources