Why select_tag displays only one column? - ruby-on-rails

I have the following select_tag in my view:
<%= select_tag :users, options_from_collection_for_select(#users, 'id','firstname' , 'lastname') %></p></br>
I want to display the firstname and lastname in the select_tag, but it always displays the first parameter after the 'id' in this case the firstname.
What I'm doing wrong?

Use this instead
<%= select(:users, :id, #users.map {|u| [u.firstname + " " + u.lastname,u.id]}) %>

Im confident that options_for_select only allows you to put 1) The value that you want each option to have, 2) The id or label you want that option to have.
What you'd do is, in your User model, set a method to concatenate both the user first and last name into one and then use that as your option_for_select id.
User Model
def userFullName
self.firstname+' '+self.lastname
end
Then use it in your select_tag as this:
<%= select_tag :users, options_from_collection_for_select(#users, 'id','userFullName') %>

From Api Doc for options_from_collection_for_select you can get this:
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
If you only want to display the options, that's is the right way to do it.
You only specify a 4th parameter if you want to preselect one option.
If you want to concatenate the name, you could do it as Oscar Valdez is telling you to.
Check more info for options_from_collection_for_select here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

Related

How do I properly use a select box with ruby on rails?

I have a select box for the event types of an event. event belongs to event_type and event_type has many events. Here's what I have for the select box:
<%= f.select :event_type, options_from_collection_for_select(EventType.all, :id, :name, #event.id), :placeholder => 'Select an event type' %>
But, the problem is that when I submit it, it submits the id of the event type and not the name of it. So, how would I make it submit the name rather than the id? If you need to see the any more code than just tell me, thanks
The second parameter to options_from_collection_for_select is the value that will be submitted with the form. You have :id, so change it to :name.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
(but this seems like a strange thing to do - typically you would store the event type ID.)
You can use the id after the submit to load the event type again in your controller post action like this:
selected_type = EventType.find(params[:event_type]
It is also a good practice to keep database calls to the controller, so please put the EventType.all statement in there and pass it as local or class variable like you did with event.
If you really want to pass the name in your form instead of the id, you can replace the :id part in your call to something more like this options_from_collection_for_select(#event_types, :name, :name, #event.event_type.name). Keep in mind that this value should be unique!
The method works like this:
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
So the first parameter contains all the options, the second defines the value within those option objects which are put into the value field of the HTML option (which is being submitted by the form), the third defines the text which is displayed to the user and the final parameter defines the value of the selected entry (in case you are editing an entry for example). For the last parameter, you need to use the events' event_type id, or in your case, the name because you set the value of your HTML tag to it.
Use pages like ApiDock or the Rails tutorials to get examples for some of these methods.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
You should pass name in the Value method, if you want to pass the name,
<%= f.select :event_type, options_from_collection_for_select(EventType.all, :name, :name, #event.id), :placeholder => 'Select an event type' %>
Here is the doc for options_from_collection_for_select

Form_for select field, concatenating data into the display string

I am trying to use a form_for collection_select to display some select field options of account types.
Its occurred to me that it would be easier for the user if they could see the price of the type in each select option
this is my currently not-working code:
<%= a.collection_select :account_type, AccountType.all, :id, (:name+" - "+number_to_currency(:price)) %>
how can i concatenate the values so that (:name+" - "+number_to_currency(:price)) will actually work and not throw an error?
See the documentation:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
You can use the :text_method option to set the displayed text in the select dropdown.
In your AccountType model, define a method like this:
def name_with_price
"#{name} - $#{price}"
end
Then, in your view, you can use:
<%= a.collection_select :account_type, nil, AccountType.all, :id, :name_with_price %>

How do I obtain a selected value in Ruby on Rails 2.3.8?

My select_tag is as follows.
<%= select_tag "group", options_from_collection_for_select(#groups, "id", "gname") %>
How do I obtain the selected value in my controller?
Use square brackets.
select_tag "group[]", options_for ....
Note the []. Rails will then store this as {"group" => [one option for each form]}.
If it's important to know which select provided which value, you can nest them, so
select_tag "group[bob]", ...
will provide {"group" => {"bob" => selected_option}}.
Basically, [] stores it in an array, and [key] stores it in a hash with that key.
Then in controller, you can use as:
params["group"], which should be an array of the various selects on the page.
Try puts params and check the your console to see values sent to the controller.
That should be params[:group] in your controller.

Array as Parameter from Rails Select Helper

I'm working on a legacy project that is using acts_as_taggable_on which expects tags to come in arrays. I have a select box allowing users to select a tag on a Course in a field called categories. The only way mass assignment create will work is if params looks like this params = {:course => {:categories => ['Presentation']}}. I've currently a view with this helper:
<%= f.select 'categories', ['Presentation' , 'Round Table' , 'Demo', 'Hands-on'] %>
Which will give me a parameter like params = {:course => {:categories => 'Presentation'}}. This doesn't work since Acts as tag gable apparently can't handle being passed anything other than a collection.
I've tried changing categories to categories[] but then I get this error:
undefined method `categories[]' for #<Course:0x007f9d95c5b810>
Does anyone know the correct way to format my select tag to return an array to the controller? I'm using Rails 3.2.3
I didn't work with acts_as_taggable_on, but maybe this simple hack will be suitable for you? You should put it before mass-assignment.
category = params[:course][:categories]
params[:course][:categories] = [category]
If you are only going to allow the selection of ONE tag, you could do:
<%= f.select 'categories', [['Presentation'] , ['Round Table'] , ['Demo'], ['Hands-on']] %>
Each one item array will have first for the display value, and last for the return value, which in this case will both return the same thing, as the first element of the array is the same as the last element when the array as one element.
Seems like select doesn't give you that option.
If I understand correctly, one option might be to use a select_tag instead and just be explicit about where you want the selection in the params:
<%= select_tag 'course[categories][]', options_for_select(['Presentation' , 'Round Table' , 'Demo', 'Hands-on']) %>
That ought to get your params the way you need them.
Here's what I'm using for one of my projects:
<% options = { include_blank: true } %>
<% html_options = { required: true, name: "#{f.object_name}[#{resource.id}][days][]" } %>
<%= f.select :days, DAYS, options, html_options %>
Without html_options[:name], Rails handles the name of the select tag and spits out something like
service[service_add_ons_attributes][11][days]
but I need
service[service_add_ons_attributes][11][days][]
So I override it.
Hope that helps.

collection_select set option value of :include_blank to zero

In my rails app, i have a drop down box where i retrieve all groups from the Group table and display them using the collection_select tag.
When the user selects 'None', I want to pass '0' as option value.
Currently, an empty string is passed.
Is there a way to include option value = 0 for 'None'?
<%= f.collection_select :SUB_GROUP, Group.all, :Group_ID, :Group_ID, :include_blank => 'None' %>
Many many thanks for any suggestion provided
If you use options_for_select in combination with select_tag you can achieve that using this:
options_for_select(
[['None', '0']].concat(
Group.all.collect { |g| [g.group_id.to_s, g.group_id.to_s] }
)
)
In order to keep your views uncluttered, you might want to generalize and move this into a helper method with a reasonable name.

Resources