Rails, collection_select - remembering values with :selected after form submitted - ruby-on-rails

(Using Rails 2.3.5 on an internal work server with no choice of versions, and I'm pretty new)
I'm building a search form where I need to provide a list of directories to a user so they can select which one(s) to search against. I'm trying to figure out how to get the selected values of a collection_select to remain after the form is submitted.
Say the user selected 3 directories from the collection_select, the id's of those directories would look like this in the params:
directory: !map:HashWithIndifferentAccess
id:
- "2"
- "4"
- "6"
I know that you can manually specify multiple selected items:
<%= collection_select :directory, :id, #directories, :id, :name,
{:selected => [2,4,6]}, {:size => 5, :multiple => true} %>
I've also played around a bit and was able to us "to_i" against a single value in the params hash:
<%= collection_select :directory, :id, #directories, :id, :name,
{:selected => params[:directory][:id][0].to_i}, {:size => 5, :multiple => true} %>
What I can't figure out is how to use all of the values of the :directory params at the same time so what the user selected remains after the form is submitted. Thanks for any help.

I'm not precisely sure what you're asking, but if you're trying to get the array of strings in params[:directory][:id] as an array of integers, all you need is
params[:directory][:id].map{|id|id.to_i}

Related

How do you make a rails multi select dropdown work

I am trying to make a multi select dropdown work with a dialog for search parameters. I can make the dropdown multi select but can't seem to get/pass the resulting data. (edited/new info will be in italics)
I believe that the root of the problem is that I need to change the permit section in my controller to reflect that I am passing a hash/array. If I look at the resulting record, the 2 fields that I am setting as multi-selects show as nil. However, if I force an errror, the parameters shown by rails show the correct choices. therefore, I believe that the problem might be with the permit section.
That looks like
*def search_params
params.require(:search).permit(:document_title,
:summary,
:owner,
:category,
:file_name,
:doc_to_email,
:categories_attributes => [:name])
end*
I added the :categories_attributes => [:name] to try to get the controller to allow hashes but that didn't work.
The select field is
<%= f.select :category[], options_for_select(#categories.sort), {:include_blank => true}, {:multiple => true, :size =>10} %>
but that gives me
.erb where line #41 raised:
wrong number of arguments (0 for 1..2) Trace of template inclusion:
app/views/searches/new.html.erb
I thought I had to set category as an array with the [] but obviously I'm missing something.
Category is a string field in the Searches table.
You do not need the [] brackets after the field name as Rails adds those in automatically.
See the example here:
http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag
select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
# => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
# <option>Green</option><option>Blue</option></select>
In your case the selected values will be available as an array in params[:search][:category] after the form is submitted.
If you use strong parameters, also make sure you have :category => [] in the permit list.

How to use :selected with grouped_collection_select

Is it possible to somehow use the :selected option that you'd use on a normal select view helper with the grouped_collection_select function? I'd like to set the value that gets pre-selected in my list. I've tried passing in :selected as an option with no luck!
Here's some code snippts of my tests:
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, { :include_blank => true, :selected => 5 }
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, :include_blank => true, :selected => 5
Neither version works. No selected is set. I'm using this to set a value for a nested model. I'm using the railscasts dynamic select list methods: http://railscasts.com/episodes/88-dynamic-select-menus-revised
I couldn't get formtastic to play nicely with the group selects so I had to do it by hand but I don't keep this value selected when a user fails validations. I'd like to keep this set when they fix validation errors.
I just ran across the same problem and solved it using the option_groups_from_collection_for_select helper and the select helper documented at: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html.
The first step is to create the grouped options. Taking your example, it should look like:
<% options = option_groups_from_collection_for_select(Trade.order(:name).all,
:subscription_plans, :name, :id, :display_name, 5) %>
Then I created the select object like:
<%= select('user[subscription_attributes]', :subscription_plan_id, options,
include_blank: true) %>
You could write it all out in one line, I just broke out the options into a separate variable to illustrate the two different methods.
Maybe too late, but the API documentation of grouped_collection_select states:
'The value returned from calling method on the instance object will be selected.'
So, you don't even have to specify a :selected option, since Rails will automatically select based on the current value of your attribute.
If subscription_plan_id has value 5, then that's what will be selected.
If that's supposed to be a default value, then you can set it with an after_initialize in your model.
Actually you need to send in options include_blank for example
<%= grouped_collection_select :id, model.all, options = {:include_blank => 'Selecione'}%>

ruby hash to rails

I have a hash of items which I'm getting via Freebase. I want to include it as I would a model inside a rails form_for.
ie (i'm using formtastic) , this works on a model...
<%= f.input :source, :as => :select, :collection => #subject.types, :member_label => :name, :member_value => :id, :input_html => { :class => 'combobox' } %>
But not on my hash.
My question is how can I use an external source with the rails form_for helpers and whether this is a route I should take. I'm sure I could take another route using the form_tag and then cycle through the simple ruby hash, but thought maybe using the rails methods would be more elegant and maintainable? I'm also not storing the freebase data, just the ID.
Simplified Array/Hash:
[{:name=>"US President", :value=>"/m/02mjmr"}, {:name=>"Election campaign", :value=>"/m/047qllg"}, {:name=>"Event", :value=>"/m/057l6lw"}]
or the complete hash of freebase search results:
[{"mid"=>"/m/02mjmr", "name"=>"Barack Obama", "notable"=>{"name"=>"US President", "id"=>"/government/us_president"}, "lang"=>"en", "score"=>156.429855}, {"mid"=>"/m/047qllg", "name"=>"Barack Obama presidential campaign, 2008, General Election", "notable"=>{"name"=>"Election campaign", "id"=>"/government/election_campaign"}, "lang"=>"en", "score"=>58.741718}, {"mid"=>"/m/057l6lw", "name"=>"Barack Obama 2009 presidential inauguration", "notable"=>{"name"=>"Event", "id"=>"/event/event"}, "lang"=>"en", "score"=>57.407536}]
You should be able to easily do this as so:
<%= f.collection_select :freebase_id, options_from_collection_for_select(#freebase_hash, :value, :name, #object.freebase_id)
The #object.freebase_id is passed to options_from_collection_for_select so that it can specify which (if any) are selected when the view is loaded. This is important for edit actions, or for new actions when redisplaying the form after validation errors.

Ruby On Rails - Showing the default option with collection_select dependent on params

I'm using an out-dated version of rails (2.2).
I have a page which has a search filter. When I filter the options, I would like the Dropdown boxes to default to the filters I selected. The filters are being stored as parameters in the URL. i.e. filter[Issue+Header]=test&filter[in4User]=1&filter[Module]=3
What I search:
http://i.stack.imgur.com/r804l.png
What I currently see when page loads (as you can see, text boxes are re-populated, but dropdowns are not):
http://i.stack.imgur.com/G83X8.png
What I want to see when page loads:
http:// [remove_this_space] i.stack.imgur.com/r804l.png
Example of a collection_select I am using:
<%= collection_select(:filter, "Client", Client.find(:all, :conditions => ['status = 0']), :ClientID, :Name, :include_blank => true) %>
What you need to do is pass in the :selected option into collection select, and pass the appropriate param as the value, so something like:
<%= collection_select(:filter, "Client", Client.find(:all, :conditions => ['status = 0']), :ClientID, :Name, :include_blank => true, :selected => params[:filter]) %>
That should select the client, assuming that the Client is in the collection.

Not setting anything in Rails' collection_select

I have a Rails 2.3 web application that uses the collection_select helper with :multiple => true to handle a habtm relationship. This is working fine to set one or multiple values, however I have not figured out how to allow to REMOVE all selections.
Code:
<%= f.collection_select :category_ids, Category.find(:all), :id, :name,
{ :selected => #entry.category_ids },
{ :multiple => true, :name => 'entry[category_ids][]' }
%>
Once the user has ever set a category for an entry, how would I go about allowing it to be removed, so that this entry has no category? Is this possible with collection_select or would I need to add a checkbox to handle this specially?
P.S: I already tried with :prompt, :include_blank and :allow_blank, but as far as I could see neither of them did anything.
In your controller's update action, put in the following line:
params[:entry][:category_ids] ||= []
before the call to Entry.find.

Resources