Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 558
T. Weston Kendall Avatar asked Jul 21 '11 01:07

T. Weston Kendall


2 Answers

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' %>
like image 174
Vedant Agarwala Avatar answered Nov 17 '22 11:11

Vedant Agarwala


(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.

like image 2
Anson Avatar answered Nov 17 '22 12:11

Anson