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

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.

Related

Rails pass id in selection instead of string

I have a select form:
<%= f.select :business_name, options_for_select(Client.uniq.pluck(:business_name)),{:include_blank => false},{:multiple=>true} %>
It picks out the distinct business_name and renders them in a selection box. I need the form to send the relevant business_id when a business_name is selected instead of sending the name string.
How do I achieve this?
options_for_select takes an array of arrays. Ideally if you want the name and value on the html select option to be different you pass in those pairs as [name, value]. By using pluck to grab only the business name you're passing in [name]--no value to put into the option tag.
change your code to use:
...options_for_select(Client.uniq.pluck(:business_name, :id))...>
You can use this:
options_for_select(Client.uniq(:business_name).collect{ |c| [c. business_name, c.id] })
So you would return all unique values on business name and the collect with name-value pair for select

Why select_tag displays only one column?

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

Ruby on Rails: combobox is showing id and not the name

I got the code
<%= f.select :wahl1, options_for_select(#berufs) %>
and im getting id´s or smth #<Beruf:0x45ed8e8> instead of the name of #berufs in the combobox
options_for_select expects a simple array or hash of keys and values. Yet you are passing it a collection of models.
What you want is options_from_collection_for_select, for example:
= f.select :wahl1, options_from_collection_for_select(#berufs, 'id', 'name')

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.

Can someone explain collection_select to me in clear, simple terms?

I am going through the Rails API docs for collection_select and they are god-awful.
The heading is this:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
And this is the only sample code they give:
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
Can someone explain, using a simple association (say a User has_many Plans, and a Plan belongs to a User), what I want to use in the syntax and why?
Edit 1: Also, it would be awesome if you explained how it works inside a form_helper or a regular form. Imagine you are explaining this to a web developer that understands web development, but is 'relatively new' to Rails. How would you explain it?
collection_select(
:post, # field namespace
:author_id, # field name
# result of these two params will be: <select name="post[author_id]">...
# then you should specify some collection or array of rows.
# It can be Author.where(..).order(..) or something like that.
# In your example it is:
Author.all,
# then you should specify methods for generating options
:id, # this is name of method that will be called for every row, result will be set as key
:name_with_initial, # this is name of method that will be called for every row, result will be set as value
# as a result, every option will be generated by the following rule:
# <option value=#{author.id}>#{author.name_with_initial}</option>
# 'author' is an element in the collection or array
:prompt => true # then you can specify some params. You can find them in the docs.
)
Or your example can be represented as the following code:
<select name="post[author_id]">
<% Author.all.each do |author| %>
<option value="<%= author.id %>"><%= author.name_with_initial %></option>
<% end %>
</select>
This isn't documented in the FormBuilder, but in the FormOptionsHelper
I've spent quite some time on the permutations of the select tags myself.
collection_select builds a select tag from a collection of objects. Keeping this in mind,
object : Name of the object. This is used to generate the name of the tag, and is used to generate the selected value. This can be an actual object, or a symbol - in the latter case, the instance variable of that name is looked for in the binding of the ActionController (that is, :post looks for an instance var called #post in your controller.)
method : Name of the method. This is used to generate the name of the tag.. In other words, the attribute of the object you are trying to get from the select
collection : The collection of objects
value_method : For each object in the collection, this method is used for value
text_method : For each object in the collection, this method is used for display text
Optional Parameters:
options : Options that you can pass. These are documented here, under the heading Options.
html_options : Whatever is passed here, is simply added to the generated html tag. If you want to supply a class, id, or any other attribute, it goes here.
Your association could be written as:
collection_select(:user, :plan_ids, Plan.all, :id, :name, {:prompt => true, :multiple=>true })
With regards to using form_for, again in very simple terms, for all tags that come within the form_for, eg. f.text_field, you dont need to supply the first (object) parameter. This is taken from the form_for syntax.

Resources