I have a complex form (like Ryan B's Complex Form Railscasts) where I have a few levels of database tables being altered at the same time.
The code for this dropdown box works in that it delivers the correct integer to the database. But, despite numerous attempts I cannot get it to correctly reflect the database's CURRENT value. How can I sort out this code?
<%= o.select :weighting, options_for_select([
["Correct", "4", {:class=>"bold"}],
["Good", "3"],
["Average", "2"],
["Poor", "1"],
["Incorrect", "0", {:class=>"bold"}] ], :weighting), {},
html_options = {:class => "listBox", :style=>"float:left;"} %>
Thanks.
You're on the right track, but not quite there.
While the final argument to options_for_select should be the value of the selected option. The value you supply :weighting is a symbol that does not match the value of any of your given options.
You will need to give the actual value. If you used an instance object to build the form as in
<%form_for #whatever do |o|%>
...
You can simply used #whatever.weighting.to_s as in:
<%= o.select :weighting, options_for_select([
["Correct", "4", {:class=>"bold"}],
["Good", "3"],
["Average", "2"],
["Poor", "1"],
["Incorrect", "0", {:class=>"bold"}] ], #whatever.weighting.to_s), {},
html_options = {:class => "listBox", :style=>"float:left;"} %>
Otherwise, there's a way to get the object off the form block variable o. But that's messing with internals which may change with an upgrade.
Edit: In the case where you're working with fields for and multiple partials, you can get the particular object off of the form builder block variable.with the object accessor.
Reusing the above example something like this to use the current weighting of each child instance in that instance's section of the form.
<% form_for #parent do |p| %>
...
<% p.fields_for :children do |c| %>
...
<%= c.select :weighting, options_for_select([
["Correct", "4", {:class=>"bold"}],
["Good", "3"],
["Average", "2"],
["Poor", "1"],
["Incorrect", "0", {:class=>"bold"}] ], c.object.weighting.to_s), {},
html_options = {:class => "listBox", :style=>"float:left;"} %>
...
<% end %>
<% end %>
This can also be used in partials.
Second try =)
<%= f.label :priority %>
<%= f.select(:priority, options_for_select({"Stat" => "1", "Urgent" => "2", "Regular" => "3", "Safety" => "4"}, #servicerequest.priority), :prompt => "Choose") %>
Related
I am trying to pass to my select_tag both fixed values and loop values. I can perfectly write something like :
<%= select_tag "", options_for_select(session[:user_hotel_list].collect{ |hotel| [hotel["name"], hotel["id"]] }) %>
Here hotel["name"] will be the displayed value and hotel["id"] the "real value" of the field.
But if I try to add extra fixed values to my options_for_select I dont get the desired output. Let's say I want to add a select with "all hotels" with a value of "all". I would try something like that :
<%= select_tag "", options_for_select([["all hotels", "all"], session[:user_hotel_list].collect{ |hotel| [hotel["name"], hotel["id"]] }]) %>
But here I would get an array as output for the collection...
How can I correctly add extra fixed data to an options_for_select with a collection in rails ?
EDIT
For example this code :
<%= select_tag "dash_select", options_for_select( [["all hotels", "all"], ["other", "value"]] << session[:user_hotel_list].collect{ |hotel| [hotel["name"], hotel["id"]] }) %>
outputs this :
and obviously ["plaze", 31] isnt good !
Do you really need to add multiple items? Or is your example with just "All hotels" sufficient. Because in that case you could just do:
<%= select_tag "", options_for_select(...), { include_blank: "all hotels" } %>
I have an array like this:
['New York', 'Los Angeles']
And I want to be able to generate a select/option with those values in a form like this:
<%= form_tag filter_city_path, :method=> get do %>
<%= select_tag "city", #list_of_cities %>
<% end %>
But this is not working. As you can see I want to pass the selection as city in the url.
You need to use options_for_select helper like
<%= select_tag "city", options_for_select([['New York' ,'New york'], ['Los Angeles', 'Los Angeles']]) %>
My method for this is to build the array as a constant in the model, force confirmation to options listed in the constant, and call it from the view
class Show < ApplicationRecord
DAYS = [ "monday", "tuesday", "wednesday", "thursday","friday", "saturday","sunday"]
validates :day, inclusion: DAYS
end
If you want the option for that field to be submitted without content you'll have to call `allow_blank: true' in the validation as well. Once that is set up you can call the constant to populate the view in the form as so:
<%= select_tag "day", options_for_select(Show::DAYS) %>
or
<%= select_tag "day", options_for_select(Show::DAYS.sort) %>
if you want it presorted (which makes no sense with days of the week...)
It looks like your array doesn't have enough argument. Please refer to this guide.
The options typically needs to be formatted in this way:
[['Lisbon', 1], ['Madrid', 2], ...]
Take note the value 1, 2, etc.
I'm trying to figure out how to properly handle the params hash so as I dont pass params that should be nested multiple times..
Here is a simplified(removed not-needed info like labels etc) of my html.slim code (using simple_form):
= f.simple_fields_for :room do |r|
- (1..4).each do |room|
= r.input 'adults',:collection => 1..4,:input_html => {:name => "room[adults][]"}
= r.input 'children',:collection => 0..2,:input_html => {:name => "room[children][]"}
- (1..2).each do |child|
= r.input 'child_age',:input_html => {:name => "children[#{child}][ages][]"}
ok this with inputs of 1 room, 1 adult,1 child of age 5 we get params like this :
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1", "0"]}, "children"=>{"1"=>{"ages"=>["5", ""]}, "2"=>{"ages"=>["", ""]}}
what I actually want to have on params is this:
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>["1"=>["5",""], "0"=>["",""]] }
anyone got any idea on how to do that?
Sorry, I don't know how simple_form works, but here's how I would do it in with normal rails helpers.
<%= f.fields_for :rooms, (rooms_collection) do |r| %>
... # Any inputs you may want
<%= r.fields_for :children, (children_collection) do |c| %>
<%= c.text_field :child_age %>
This won't give you the exact input you want but it will give you something like
"room"=>{"adults"=>["1", "1", "1", "1"], "children"=>{"0"=>{child_age => ["5",""]}, "1"=>{child_age => ["",""]}}}
Alternatively if you don't have persisted objects this should work
<%= f.fields_for :rooms do |r| %>
... # Any inputs you may want
(1..2).each do
<%= r.fields_for :children do |c| %>
<%= c.text_field :child_age %>
my routes for a specific controller of my application are (i create them manually):
scope :path => '/labor', :controller => :labor do
get '/' => :index, :as => 'labor'
post 'start/:work_hours' => :start, :as => 'start'
post 'stop' => :stop, :as => 'stop'
end
I'm creating a form_tag, but i'm having problems passing the posted value. My form currently is :
<%= form_tag start_path do %>
<%= select_tag :work_hours, options_for_select([ "1", "2", "3", "4", "5", "6", "7", "8" ], "1") %>
<%= submit_tag "#{t 'labor.start_work'}" %>
<% end %>
I would expect that to work, but unluckily, it does not and i don't understand why. I actually get a routing error No route matches {:controller=>"labor", :action=>"start"}
Why is this happening and how can i fix it, so that the :work_hours is properly posted from the form ?
you can actually try
<%= form_for :start_labor do %>
<%= select_tag :work_hours, options_for_select([ "1", "2", "3", "4", "5", "6", "7", "8" ], "1") %>
<%= submit_tag "#{t 'labor.start_work'}" %>
<% end %>
then update your data n controller iwith params[:start_labor][:work_hours]. That worked fine for me
I've got a model that has a serialized hash as a field. I'm trying to create a form that enables users to fill this out. Is there a way to use Rails form_for helper to concisely build the hash?
The model is an Article, and an Article can have many authors which are stored in a serialized hash.
class Article
serialize :authors, Hash
end
The authors hash stores information about each author that contributed to the Article, and can have many optional attributes. The authors are keyed by the order in which they should appear. Here is an example of what such a hash may look like:
{1 => {:name => "William Jones", :contribution => "Wrote the body of this question"}, 2 => {:name => "Billy Bob", :contribution => "Got coffee for William", :level => "Minor"}
I've got a form that kinda works for this, where I use the form_for Rails helper, but I'm forced to use text_field_tag and other non-model specific helpers to generate the authors hash. For example, where key_num is a variable passed into a partial:
<%= text_field_tag "article[authors][#{key_num}][name]",
article[authors][#{key_num}] ? article[authors][#{key_num}][:name] : nil %>
Obviously, this is pretty darn ugly and unclear. Is there a better way to do this I'm missing?
I'm versioning the Articles, and for that among other reasons, it is hugely helpful to use a serialized Hash instead of spinning this authors concept into a separate sub-model.
I'm trying to do something similar and I found this sort of works:
<%= form_for #search do |f| %>
<%= f.fields_for :params, #search.params do |p| %>
<%= p.select "property_id", [[ "All", 0 ]] + PropertyType.all.collect { |pt| [ pt.value, pt.id ] } %>
<%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %>
<%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %>
<% end %>
<% end %>
except that the form fields aren't populated when the form is rendered. when the form is submitted the values come through just fine and i can do:
#search = Search.new(params[:search])
so its "half" working...