Rails 4 form: display database value in select field - ruby-on-rails

There are similar questions on Stack Overflow, like this one or that one, and I tried what the answers recommended, but I could not fix my problem.
I have a Rails form — NOT a simple_form form — with the following field in my new view:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'] %>
</div>
Then, I want to re-display this form in my edit view, with the value that was saved to the database, so I tried:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'], :selected => current_user.price %>
</div>
The problem is that the select field displays the first value instead of the one I am expecting.
—————
UPDATE: Following the answers given below, I implemented the following code:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %>
<%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>
It does not seem to work. Unless I made a mistake?
—————
Any idea how to make this work?

You don't need two separate forms.
in new.html.erb and edit.html.erb put the following:
<%= render 'hourly_rate' %>
then in _hourly_rate.html.erb put the following:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %>
<%= f.select :price, options_for_select([['10',1], ['20',2], ['30',3], ['40',4], ['50',5], ['60',6], ['70',7], ['80',8], ['90',9], ['100',10]], #your_obj.price) %>
</div>
where #your_obj.price is something like 1, 2, 3...(or you can modify this to the actual prices if you'd prefer. You'd just need to change the arrays accordingly).
The options_for_select method is a helper whose second parameter allows you to pre-select an option by passing its value. For more on that, take a look at the docs.

try this:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']], selected: current_user.price, include_blank: 'Select your price' %>
</div>
you should pass an array of arrays which the left cell is the name and the right one is the value, then pass in selected by value and not by name, you should use this also in the first form:
<div class="field">
<%= f.label :price, "Hourly Rate ($)" %><%= f.select :price, [['10', '10'],['20','20'],['30','30'],['40','40'],['50','50'],['60','60'],['70','70'],['80','80'],['90','90'],['100','100']] %>
</div>

Related

Changing f.select to checkbox

I have the following in my view at which the can select several categories:
<%= form_for(#survey) do |f| %>
Categories <br>
<%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %><br>
<%= f.submit %>
<% end %>
I want the user to be selecting the categories with checkboxes instead of drop down list.
I am not sure how this is possible. Two parts: 1. How it will display several checkboxes and 2. How it will be saving the user's selections as it is saving fine for the f.select above.
The approach (which is not complete) that I though of is to iterate through the categories and add a checkbox for each category. However I am not sure if this will make sure that the several selections will be saved.
<% #categories.each do |category| %>
<%= category.name %><br>
<%= f.check_box :category_ids %>
Any guidance/tip to the right direction is greatly appreciated.
You can use collection_check_boxes
<%= f.collection_check_boxes :category_ids, Category.all, :id, :name, {}, :multiple => true %><br>

Ruby on rails. Set a form field as nil/blank from controller

I am trying to let users RELIST 'gigs' that they have previously posted by duplicating the old one and saving it with a new ID. At the moment everything duplicates fine and can be saved but I need one of the fields (datetime) to be blank as it is vital that they manually set this. I do not know how to set this as nil/blank from the controller.
Relist link:
<%= link_to t('gigs.show.relist'), gig_relist_path(:gig_id => #gig.id), class: 'gig-edit-dash' %>
Gig controller:
def relist
#oldgig = Gig.find(params[:gig_id])
#gig = #oldgig.dup
end
Form:
<div class="create-form">
<%= simple_form_for #gig do |form| %>
<div class="create-title">
<%= form.input :title, label: t('gig.title'), placeholder: t('placeholder.title') %></div>
<div class="create-location">
<%= form.input :location, label: t('gig.location'), placeholder: t('placeholder.location') %></div>
<div class="create-genre">
<ul></ul>
<%= form.label :genres %>
<%= select_tag "choose_genres", options_from_collection_for_select(Genre.all, 'id', 'name',#gig.genres.map{ |j| j.id }), :multiple => true %> </div>
<div class="create-description">
<%= form.input :description, as: :text, label: t('gig.description'), placeholder: t('placeholder.description') %></div>
<div class="create-date">
<%= form.input :date, label: t('gig.date'), placeholder: t('placeholder.date') %></div>
<div class="create-salary">
<div class="salary-input">
<p class="salary-title"> <%= t('gig.salary') %> </p>
<%= form.input :salary_currency, label: false,
collection: ["€", "£", "$" ], prompt: "Choose one" %>
<%= form.input :salary, label: false, placeholder: t('placeholder.salary') %>
</div>
</div>
Setting the default value to nil/blank in the form doesn't work as a value is being passed.
#gig.date = nil
doesn't work either, this sets the time to the current time.
Oh dear, I just figured this out about 2 minutes after posting the question. I'll leave the answer rather than deleting the post just in case someone else finds it useful.
I set #gig.date = nil in the controller after #gig = #oldgig.dup
Then added , :include_blank => true to the form field in the view.
The reasoning is pretty self explanatory.

How do I enable multiple selection for option_form_collection?

I can't figure out how to enable multiple selection for a input in Ransack.
<%= search_form_for #q,url: search_table_path do |f| %>
<%= f.label :country_code_eq %>
<%= f.select :country_code_eq,
options_from_collection_for_select(Country.all, :code, :name),
{prompt: 'Select a Country',multiple: true,include_blank: false}%>
<%= f.label :date_start %>
<%= f.text_field :date_start %>
<%= f.submit %>
<% end %>
The multiple: true does not work as I expected. It only show a normal dropdown box not a multiple selection box.
My first question is how to enable multiple selection ?
And my Second question is how do I keep the selected value and show it after the page loaded in selection box ?
I found the answer
<%= f.select :country_code_in, Country.all.map {|country| [country.name,country.code] }, {include_blank: 'All'}, {multiple: true} %>

How to populate a dropdown with database entries in Rails 4

I'm fairly new to rails and I'm building my first app. I've searched the web for a correct answer but couldn't find any that worked for my case.
I'm using simple form, with rails 4 and bootstrap 3. I have a :location dropdown on a (#employees) model and I want to populate it with a job_title column from my #positions model. I've used a scaffold to generate my position MVC + job_title:string job_description:string.
How can I populate my :location dropdown (on my employees form) with values from :job_title (from #positions model)? I currently have my code as:
<div class="col-md-6 pad-10">
<% options = options_from_collection_for_select(#positions, 'id', 'job_title') %>
<%= f.select :location, options, :input_html => { class: "form-control" } %>
</div>
But as you know, that doesn't work. Any help is appreciated!
Solution:
<div class="col-md-6 pad-10">
<% options = options_from_collection_for_select(Position.all, 'id', 'job_title') %>
<%= f.select :location, options, :input_html => { class: "form-control" } %>
</div>
I used Position.all instead of #positions.
options_from_collection_for_select needs an Array. Docs
So try using Modelname.all instead of #positions or re-declare #positions with #positions = Modelname.all
Because you are using simple_form, you can render a select box for a collection like this:
<%= f.input :location, collection: #positions, label_method: :job_title, value_method: :id, input_html: { class: "form-control" } %>
This should do it for you if you want the id ofan Position object be written to the location field. If you want the job_title cahnge :id to :job_title.
<div class="col-md-6 pad-10">
<%= f.label :location %><br />
<%= f.collection_select :location, #positions, :id, :job_title %>
</div>
I used Position.all instead of #positions.
<div class="col-md-6 pad-10">
<% options = options_from_collection_for_select(Position.all, 'id', 'job_title') %>
<%= f.select :location, options, :input_html => { class: "form-control" } %>
</div>

Using select_month in form_for

I am working in Ruby on Rails and I cant figure out how to use select_month in a form_for. What I am trying is:
<%= form_for(#farm) do |f| %>
<div class="field">
<%= f.label :harvest_start %><br />
<%= select_month(Date.today, :field_name => 'harvest_start') %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
which is outputting
["harvest_start", nil]
In order to use select month consistently with the rest of your form builder, use date_select without the day or month:
date_select(object_name, method, options = {}, html_options = {})
Just use f.date_select :harvest_start, {order: [:month]} i.e. add order: [:month] or discard_year: true, discard_day: true to the options hash, as specified in the docs
The benefit of this you can pass in all the remaining options as you would in the options hash. Something like:
<%= f.date_select :birth_date, {prompt: true, order: [:month]}, class: 'form-control' %>
(this was answered in comments by T. Weston Kendall so just making it a proper answer)
the following code is what i got to work.
_form.html.erb
<div class="field">
<%= f.label :harvest_start %><br />
<%= f.collection_select :harvest_start, Farm::MONTHS, :to_s, :to_s, :include_blank => true %>
</div>
farms_controller.rb
#farm.harvest_start = params[:harvest_start]
i also got select_month to work but i needed the :include_blank and i didn't want to spend the time figuring out what to do with the nil in an array.

Resources