I have number of select lists in my rails application like this:
<li>Company<span><%= f.select :company_id, Company.all.collect {|m| [m.companyname, m.id]} %></span></li>
They all work well, except - sometimes if you go to the edit view, the select list reverts to the top item, not the item that was chosen when creating. So if you go to an edit view and then click update without actually making any changes, the lists default to the top item - even though you didn't touch them.
Is there a way around this?
Thanks,
Danny
EDIT:
<% form_for (#kase), :html => { :multipart => true } do |f| %>
<li>Appointed Surveyor<span><%= f.select :appointedsurveyor_id, Company.all.collect {|m| [m.companyname, m.id]}, {:selected => #kase.appointedsurveyor_id} %></span></li>
<li>Surveyor Name<span><%= f.select :surveyorperson_id, Person.all.collect { |x| [x.personname, x.id]}, {:selected => #kase.surveyorperson_id} %></span></li>
I have tried the above, but sadly it still seems to revert to the default value.
I'm stuck on this, I can't find any tutorials etc on this at all.
EDIT 2:
<li>Appointed Surveyor<span><%= f.select :appointedsurveyor_id, Company.all.collect {|m| [m.companyname, m.id]}, {:selected => (#kase.appointedsurveyor_id rescue "")} %></span></li>
<li>Surveyor Name<span><%= f.select :surveyorperson_id, Person.all.collect { |x| [x.personname, x.id]}, {:selected => (#kase.surveyorperson_id rescue "")} %></span></li>
You might be able to make sure of it with the third parameter, try the following code:
<li>Company<span><%= f.select :company_id, Company.all.collect {|m| [m.companyname, m.id]}, {:selected => #your_instance_name.company_id} %></span></li>
Make sure that you replace #your_instance_name with the instance variable you use at the form_for tag.
Hopefully that helps.
It turns out I had the fields in the database as strings not integers.
Related
I've got a group which has many clients.
The moment the user wants to delete the group, he's obligated to move the clients of that group to a different group.
So i've created a little form. But I already know it's wrong. but I don't know how I should do it otherwise.
I want the form to be caught by my disband_group method in my groups controller. Extract the move_to ID etc.
This is what I have now. Which doesn't work.
(it says param not found: group on params.require(:group) which is no big surprise)
<%= form_for(#group) do |f| %>
<%= select_tag('move_to', options_for_select(current_user.groups.collect{ |u| [u.name, u.id] }), :prompt => "Choose") %>
<%= f.submit "Move" %>
<% end %>
The select_tag needs to be changed to f.select. That should do the trick.
After that if it still does not work, put a 1/0 as the first line in the method to check the parameters coming in. This will throw an exception and the page will display the parameters.
Add a route to your disband_group action (add the correct path):
post '/disband_group' => "groups#disband_group", :as => :disband_group
And then modify your form pointing to the disband_group action:
<%= form_for(:group, url: disband_group_path) do |f| %>
<%= f.select :move_to, options_for_select(current_user.groups.collect{ |u| [u.name, u.id] }), :prompt => "Choose") %>
<%= f.submit "Move" %>
<% end %>
This will add send the move_to param as follows: "group" => { "move_to" => "3" }
Take a look to this to understand how the form works.
I am editing a Rails 2 application. In it, a user submits a form that includes a dropdown menu, and that information creates a record in my database. When the user goes to edit the record, I want to show the saved "selected" option in the dropdown menu. I keep getting errors, however. Here is my set-up:
View Select Field
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.select :start, options_for_select(#itinerary.locations), {:include_blank => true}, {:id=>"startdrop" } %>
Form Helper
def options_for_select(locations)
locations.map do |l|
content_tag "option", l.masterlocation.name, location_option_attributes(l)
end.join("\n")
end
private
def location_option_attributes(location)
{
:value => "#{location.masterlocation.street_address}, #{location.masterlocation.city}, #{location.masterlocation.state}, #{location.masterlocation.zip}",
:id => location.masterlocation.id,
:"data-masterlocation-name" => location.masterlocation.name,
:"data-masterlocation-id" => location.masterlocation.id,
:"data-masterlocation-latitude" => location.masterlocation.latitude,
:"data-masterlocation-longitude" => location.masterlocation.longitude
}
end
I have tried making the view look like this:
<%= f.select :start, options_for_select(#itinerary.locations, #newsavedmap.start), {:include_blank => true}, {:id=>"startdrop" } %>
But I get wrong number of arguments (2 for 1)) for that line. Also tried
<%= f.select :start, options_for_select(#itinerary.locations), {:selected => #newsavedmap.start, :include_blank => true}, {:id=>"startdrop" } %>
But nothing is preselected when I go to edit the saved map. I've tried following these links, and keep striking out. Appreciate any help you have to offer!
Rails select helper - Default selected value, how? , Rails form_for select tag with option selected , Rails select helper - Default selected value, how?
You could try something like this in your helper
def options_for_select(locations, selected=nil)
locations.map do |l|
tag_options = location_option_attributes(l)
if l == selected
tag_options[:selected] = "selected"
end
content_tag "option", l.masterlocation.name, tag_options
end.join("\n")
end
then call field like you were trying before.
<%= f.select :start, options_for_select(#itinerary.locations, #newsavedmap.start), {:include_blank => true}, {:id=>"startdrop" } %>
You can pass one more parameters to select the value like this:
<%= f.select :start, options_for_select(#itinerary.locations), :selected => #newsavedmap.start, {:include_blank => true}, {:id=>"startdrop" } %>
There are so many results for this search on google, and it's even asked at SO - but the solutions discussed so far are not helping me. Here's the issue: I have a form_for #company |f| and I am using f.collection_select for company_status_id - but when the form loads, I want the actual company status selected if it is set. Through the debugger I know, that it's been set, yet I am getting a default value displayed there. Here's the code:
= puts #company.company_status_id
= f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => #select_value}
Here's the generated htmnl
<select id="company_company_status_id" prompt="-Select-" name="company[company_status_id]">
<option value="1">-Not Available-</option>
<option value="2">Active</option>
<option value="3">Bankrupt</option>
<option value="4">Acquired</option>
</select>
And the conditions remain the same even if I do:
f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => #select_value, :selected => :selected => #company.company_status}
Or
f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => #select_value, :selected => #company.company_status}
This is what I finally did:
f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => #select_value, :selected => #company.company_status_id.to_i}
I read on of the answers on a similar question that collection_select automatically selects the selected value by making comparisons of what is passed with the attributes of collection. apparently there was a difference of their types, and comparing the int from CompanyStatus to the int of #company.company_status_id.to_i worked out. Though #company.company_status_id is supposed to be int as well. I can see that in the db. Anyway, it this line of code worked.
If anyone can exaplain, I will be much thankful!
If you use collection_select helper, syntax is very simple:
<%= f.collection_select :category_id, Category.all, :id, :name,
prompt: true, selected: #product.category_id %>
I hope this help
<% form_for(#company) do |f| %>
<%= f.select(:company_status_id, ListCache.all.map {|lc| [lc.name, lc.id]} ) %>
<% end %>
Sometimes you just need to go to the browser address bar and press enter. Normal reloading the page clicking the refresh button doesn't help. My problem was solved that way.
Use select_tag instead
<%= form_for(#product, :html => {:multipart => true}) do |f| %>
<%= select_tag("product[category_id]", options_for_select(#categories.map { |cat| [cat.name, cat.id] })) %>
<%end%>
Hope this help you.....
I've built a multi-select form (from within form_for) like this:
<div class="rounded-block quarter-wide radio-group">
<h4>Exclude customers from source:</h4>
<%= f.select :excluded_sources, options_for_select(User.select(:source).group(:source).order(:source).map {|u| [u.source,u.source]}), {:include_blank => false}, {:multiple => true} %>
<%= f.error_message_on :excluded_sources %>
</div>
this works well for what I need. The only problem is that when i go back to the page that displays the choices, I don't see what was previously selected (i.e. what is already in the DB at time of rendering). Is there an easy way to get rails to display what's previously been selected? I'd MUCH prefer not to switch to check boxes.
in my matching profiles model (corresponding to the table that stores excluded_sources), i have this:
serialize :excluded_sources
this ended up being the relevant piece:
:selected => matching_profile.send(:excluded_sources)
here:
<div class="rounded-block quarter-wide radio-group">
<h4>Exclude customers from source:</h4>
<%= f.select :excluded_sources, options_for_select(User.select(:source).group(:source).order(:source).map {|u| [u.source,u.source]}, :selected => matching_profile.send(:excluded_sources)), {:include_blank => false}, {:multiple => true} %>
<%= f.error_message_on :excluded_sources %>
I have a select tag nested in my form and I am needing to delete an item from my options_for_select array if it equals the word English
code:
<%= fields_for :users_languages do |u| %>
<div class="field">
<%= u.label :Assign_Languages %><br />
<%= select_tag :language_id,
options_for_select(Language.all.collect {|lang|
[lang.english, lang.id].delete_if {lang.english == "English"}
}, #lang_list),
:multiple => true,
:prompt => 'Select Language' %>
</div>
<% end %>
Problem:
The above code works fine, but for some reason the first option is still shown in the mutli-select producing a blank select option. Is there anyway to get rid of the select option and its value? Am I even doing this correctly?
Thanks for all the help in advance!
You can do it using a collect and a reject.
Language.all.collect { |lang| [lang.english, lang.id] }.reject { |(lang, id)| lang == 'English' }
Not sure how to do it using just collect.
I realize this is a year old, but for the sake of future googlers...
Rather than inlining SQL, you might be better off with a named scope:
scope :not_english, where("english != 'English'") # Rails 3
or
named_scope :not_english, :conditions => "english != 'English'" # Rails 2
which will let you do:
options_for_select(Language.not_english.collect {|lang| [lang.english, lang.id]})
That is easier to read, more expressive, and not depending on some magic database id.
Cheers!
(PS: Also, you may want to consider updating your schema so the name of the db column isn't confused with it's value. May I suggest language.name, rather than language.english?)
It looks like your selection is actually returning an empty array as the first element. Try pulling out the unwanted option first:
Language.all.reject {|lang| lang.english == "English}.collect {|lang| [lang.english, lang.id]}
Thanks for the reply guys! What I ended up doing was handle it in my query
code:
<%= fields_for :users_languages do |u| %>
<div class="field">
<%= u.label :Assign_Languages %><br />
<%= select_tag :language_id, options_for_select(Language.find(:all, :conditions => "id != 1").collect {|lang| [lang.english, lang.id]}, #lang_list),:multiple => true, :prompt => 'Select Language' %>
</div>
<% end %>
the first row in the database will always be the same so this was easy to do in the query... although the suggestions above will come in handy in the future! Thanks again!