Value not retained in the dropdown - ruby-on-rails

I am using the simple form in my application where I have a drop down. The code is as:
<%= f.select :assigned_to, options_for_select(#user_members.collect{ |u| [u.name,u.id] }, :selected =>"#{#task.assigned_to}"), :prompt => "Assign To"%>
The issue that I am facing is that the value is not retained in the drop down after refreshing the page even though I have used :selected also.

The selected field's value should be pased in the params, so you can use that as the selected. Use the "pry" gem to debugg, your development life will become much easier :)
Try that and let me know how it went. Also, could you the code from your controller?

Related

simple_form select collection populated by AJAX

I thought this would be fairly easy, but I'm not finding any help by Googling.
I have a form (simple_form) with numerous inputs with select lists (collections) that are populated from the database, so many it is slowing down the initial page load. I thought I could speed it up by only populating those drop down lists as the user selects them using Ajax. Is there something built in like remote => true for the form itself? Can someone point me in the right direction?
EDIT:
I found this SO question but I cannot figure out how to implement the answer.
Currently, my form looks like this;
= simple_form_for(#account)
= f.input :account_number
= f.input :area, collection: #areas
= f.submit nil, :class => 'btn btn-primary'
Based on the answer in the linked question, I should add something like this, but of course it is not working
= simple_form_for(#account)
= f.input :account_number
= f.input :area, collection: #areas, :input_html => {"data-remote" => true, "data-url" => "/my_areas", "data-type" => :json}
= f.submit nil, :class => 'btn btn-primary'
I can think of two ways to go about this if you don't want to load the contents initially when the page loads. One way is to run a script after the DOM has loaded to change the options for the select tag and the other is to collect the options when you click on the drop-down on the select element. I might go for the first way because there wouldn't be latency when a user clicks on the select element--they wouldn't have to wait for the options to populate.
So you'd run a jQuery script on document ready that makes an AJAX call to a method in your controller, which then returns the collections you want, then you iterate through the select elements you want to change with JQuery scripts. It might look something like this.
# in view with the select options to be changed
$(document).ready(function() {
$.get(change_selects_path, function(response) {
$.each(response, function(args) {
// code for each select element to be changed
$('.class_of_select_element').html(<%= j options_from_collection_for_select(args) %>);
});
});
)};
# in controller
def change_selects
# make db calls and store in variables to feed to $.get request
end
Note that this not tested but should give you a good start towards a solution. For further info on the each loop, you can check out this documentation.
Not sure if this fits your exact use case (please clarify if not), but I also have a few collection selects that have a large amount of database rows behind them. I use the select2-rails gem to take care of this. Users can begin to type in the name and the relevant results will show up (it will also show a few initially if they don't type something).
Check it out here: https://github.com/argerim/select2-rails
Edit: For a cascading dropdown, I recommend this gem: https://github.com/ryanb/nested_form

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'}%>

formtastic check_boxes using collection not saving checked items in edit form

I know this was supposed to be fixed in Formtastic 2.0 but for some reason, this isn't working for me.
<%= f.input :gender, :as => :check_boxes, :collection => ["Male", "Female", "Unisex"] %>
Whenever I go back and check it, the items is always unchecked again. It never appears as selected. I know Justin French commented about it here, but I am not sure what it means or how that can help me fix the problem.
I am saving gender as a string in the User model if it makes a difference.
I am also using it with formtastic-bootstrap 1.1.1
Thank you!

Multiple selection in RoR form_for

I have a list of items that I want to have as options for a variable. They will be saved in the model as an array, and are to be displayed as a list in the form_for. I was using
f.select(:var_name, [["option1"],["option2"],["option3"]], {}, {multiple: "multiple"})
Which works great to save into the model.
But when going back to the form, nothing is selected (even if the variable has them all saved). Then if I submit the form again, it passes an empty array. The only way for it to save correctly is to re-select the ones I want every time I view the form.
How can I get them to pass into the multi-select box?
I believe your problem stems from your choices parameter. You probably need an array of [option,id] mappings:
f.select(:person_id, Person.all.collect {|p| [ p.name, p.id ] }, {}, { :multiple => true })
When I started working on it again today, it was working. I'm not sure what change was made, but it could be that I needed to restart the server. It still looks like
f.select(:name, [[" "],["option"],["option2"],["option3"]], {}, {:multiple => true})
So it must not have been this code. In addition, the form beginning looks like
form_for(#model_name) do |f|
which hasn't changed either.
Regardless, it works now. Thanks!

select(object,...) how to get the html options for this type of drop down menu

I'm using this drop down menu for my associations:
<%= select("price", "product_id", Product.all.collect {|p| [ p.name, p.id ] }, {},{ :class=>'chzn-select'}) %>
I was able to get he :class but how do i get other options such as :placeholder and :size?
Help would be highly appreciative, i cant find examples using select only after research.
P.S. Is there a better way to handle this? I am trying to make it more human friendly.
By placeholder do you mean prompt? In that case you'd put it in that first, empty hash, the 3rd argument, for helper options. The fourth is for any and all html tag options.
Edit: By placeholder do you mean HTML5's placeholder? Does that even apply to <select> tags? In any case, the same options hash where you specified the class would the place for any valid HTML options.
There are some example in the docs
For "better" options in this case #collection_select would be applicable, e.g.:
collection_select(:price, :product_id, Product.all, :id, :name, {:prompt => true}, :class => 'chzn-select')
"Better" is your call when it comes to Rails standard form helpers though. They tend to be rather inconsistent and have about umpteen ways of expressing the same thing, so just do what you're most comfortable with.

Resources