Select Box not filling properly in rails - html

I am creating a select box for a form using this in _form.html.erb
<%= f.select(:category_id,options_for_select(#cats)) %>
#cats is an array created in my controller like this:
#cats = []
categories.each do |c|
#cats.push([c.full_name,c.id])
end
The select box is properly filled, and the selected foreign key is even properly saved to the database. The problem is, when I come back in my edit action, the select box is moved back to the first item in the list, not the one corresponding to category_id. Reading the documentation it seems like this should just magically work. How do I get it to select the proper value?

When you use the select helper you just pass the choices not the full option tags like you would with the select_tag helper. Try this instead
<%= f.select(:category_id, #cats) %>

Related

Rails 5 Select tag inserts "[ ]", %5B %5D in html search string

I'm trying to use a rails select form field to populate multiple fields in a search form. But the search string returned has erroneous [] brackets inserted.
https://test-selects.c9users.io/cars?utf8=✓&car_year%5Bcar_year%5D=2016&commit=Search+Cars
proper format should be:
https://test-selects.c9users.io/cars?
utf8=✓&car_year=2016&commit=Search+Cars
<%= form_tag(cars_path, :method => "get", id:"search-form") do %>
<%= select(:car_year, :car_year, ["2017", "2016", "2015"]) %>
<%= submit_tag "Search Cars", class: "search-but" %>
<% end %>
The code above is a simplified version using just a few sample years but it yields the same results as when I was returning an array from my model that held the data for the select field.
select(:car_year, :car_year,...
I've tried every combination of :car, params[car_year] etc. and the brackets alway show up.
The same code works fine in a post method. When I provide a properly formatted search URL the search provides the expected results, I can also get expected results when I use a text_field_tag so I know my controller and model are working properly.
Help for this rookie would be greatly appreciated.
Code show above was simplified but produces the same results.

How to get value from select and use it in Rails

I'm starting a little project in rails and I'm trying to make something like that:
<%= f.label :Zgłoszenie_do_działu %>
<%= f.collection_select :dzial_id, Dzial.all, :id, :nazwa, prompt: "Wybierz" %>
<%= f.label :id_pracownik %><br/>
<%= f.collection_select :pracownikid, User.find_by_dzial_id(:dzial_id), :nazwa, prompt:"Wybierz" %>
I want to get ID of "dzial" from the first select and use it to display in the second select IDs or names of users, that belong to choosen "dzial". Like you can see I was trying to make something, but anything worked for me. If it isn't possible I would be thankful, if anybody would show me how to deal with it.
If I do understand you properly, you have the following usecase: On your page you select a dzial and after that the second select field has to show all it's User ids.
Without refreshing the page
If you want to do this without refreshing the page, you can't really do it the 'rails way'. You could use for example jQuery to do an asynchronous call on change of the first select field. Then you can use the result of that call to update the second select field.
With refreshing the page
If you want to do this by only using ruby-on-rails you could trigger a refresh on the change of the first select or simply create a submit button. Then you can set the dzial_id parameter and use it to fill the second select field like you are already doing in your example.
Edit
I forgot to mention how to get the value from the select field.
By using jQuery, you could use $('#dzial_select').val()
By refreshing the page, you might want to create two seperate forms

Best practice for custom text_method in collection_select?

I have Rails app with a use case to display prices in a collection_select dropdown box. For instance, names of products and their prices, or clients and amounts owing.
I well know it's bad MVC practice to simply include the relevant helpers to get access to functions like number_to_currency, but the best I can do with a custom method on the Product or Payment model is get a value that looks like $20.2. So, it's readable but sub-optimal in that most users of the system will be expecting twenty dollars and twenty cents to be represented as $20.20.
Does anyone have any suggestions for easily customising the text_method of a collection_select?
The text_method as well as the value_method in collection_select accepts a symbol but also a lambda/proc block which will get the current collection element as a parameter. See the docs here. The lambda is executed in the context of the view so all view helpers should be available inside it.
So to get the model price formatted by a currency formatter you should be able to call collection_select like the following:
<%= collection_select :user, :payment_id, #user.payments,
:id, ->(pmt) { number_to_currency(pmt.amount) } %>
You have not shown your model associations, so this is just an example of a user having many payments for which you want to format the price in the select box text.
Abandon ship with the collection_select method, and just use select in your view:
<% options = #payments.each { |p| number_to_currency(p.price), p.id } %>
<%= f.select :payment, options %>
Since you're in the view, everything you'd expect is there, both model and helper methods.
I'm making assumptions on your HTML since you didn't give a specific example, but I think the code block above is everything you need to get going. For more details: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
If you are married to collection_select, you could always roll your own number formatter for currency; shouldn't be difficult with pure Ruby. But, the method above will be more powerful in the long run and afford your more options with helpers down the line, and let you use functions consistently across views.
I ended up building on GoGoCarl's suggestion, but moving the array generation to a helper:
module PaymentsHelper
def invoices_for_payment_select(invoice)
#invoices.collect { |i| ["#{i.client.name} - #{number_to_currency(i.outstanding)}", i.id] }
end
end
This way I can reuse the dropdown box should I need to and keep the view neat.

Rails form_for setting options and setting selected option

Another simple question i'm sure so sorry in advance but i cant seem to find a solution to what i am trying to do.
I have form with a select field (vehicle_size) that i want to populate with all existing options that are currently in the database for records that have vehicle_size set. I also want to set the selected option to whatever the option in the database is currently set to (if set) but i guess the problem that i am having is the reason that this value isn't being set already.
I currently have this code:
<%= f.select(:vehicle_size, #models.index_by {|m| m.vehicle_size}, :selected => :vehicle_size) %>
which is populating the select options correctly but in my new and edit pages (both using this form) the select menu is blank even though currently all records are be set to one of the existing options (vehicle_size may actually be blank for some records in future).
If i then select an option from the menu and save the record the vehicle_size option has a strange value. something along the lines of :
#<Model:0x007fd13e6c3790>
I'm pretty sure i'm using index_by in the wrong way so some pointers on what i'm missing would be great.
The parameters of f.select are: attribute_name,option_tags,options.
option_tags is supposed to be a string of html option tags.
There are some helpers to construct such a string from i.e. an array of values, a collection etc.: options_for_select, options_from_selection_for_select.
You have to use one of these helpers.
You can get the existing vehicle_sizees with:
Model.pluck(:vehicle_size).uniq
so your select could look like:
<%= f.select :vehicle_size, options_for_select(Model.pluck(:vehicle_size).uniq,#model.vehicle_size) %>
See the Rails Guide on form helpers.

Add instruction to drop down select box in Rails?

I am displaying a list of all users (from a Users model) in my Rails 3 application. In a helper (in this case it's Faults) I have the following:
def user_all_select_options
User.all.map{ |user| [user.name, user.id] }
end
In the view I have the following:
<%= f.select :user_id, user_all_select_options %>
This simply creates a drop down list with the first users name pre-selected as it is at the top of the list. What I am trying to do is add an instruction(?) at the top of the list that is unselectable. The idea is to prevent the top user from getting constantly accidentally set as the required user even when they don't want to be.
So rather than the select box looking like this:
I would like it to look like this:
Is this possible, if so, how??
Pass the :prompt option.
<%= f.select :user_id, user_all_select_options, :prompt => 'Select a user' %>