Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 date_select for year only

I have a form in my Rails 3 app where I want to create a select tag for just the year on a method :grad_year. I have everything working - and storing - properly using date_select and adding :discard_month and :discard_day. However when I render @profile.grad_year I get the month and day values. So I'm wondering how to store and render only the year for @profile.grad_year?

Here is the form:

<%= f.date_select :grad_year, {:start_year => Time.now.year, :end_year => Time.now.year - 95, :discard_day => true, :discard_month => true}, :selected => @profile.grad_year %>

In my migration:

t.date :grad_year
like image 401
tvalent2 Avatar asked Nov 21 '11 16:11

tvalent2


3 Answers

Rails has a select_year helper:

http://apidock.com/rails/ActionView/Helpers/DateHelper/select_year

So your code should look like:

f.select_year(Date.today, :start_year => Time.now.year, :end_year => Time.now.year - 95, :field_name => 'grad_year')
like image 185
Alex Peattie Avatar answered Nov 14 '22 23:11

Alex Peattie


Assembling all of the above from @alex_peattie's answer, I arrived at the following:

<%= select_year Date.today, :start_year => Time.now.year, :end_year => Time.now.year - 95, :field_name => :grad_year, :prefix => :profile  %>

As with the OP's question, my case was done within a form_for block, so f.select_year threw an exception. But if you just use the documented :field_name option, the tag will have the id date_grad_year and name date[grad_year] which are not what Rails expects. Using the (documented only at the very top of the API) :prefix option changes date to profile.

So this is better than the #@%$^*& html_options hash, which, despite using rails for 5 years now, I cannot seem to get right without five tries :-).

Oh Rails, how I love you, yet at the same time am sure glad Stack Overflow is around to help us all understand your delightful idiosyncrasies!

like image 27
Tom Harrison Avatar answered Nov 14 '22 22:11

Tom Harrison


This select_year function is totally screwy.

Here is finally what works:

<%= form_for(@user) do |f| %>
 <%= select_year current_user.birth_year, { :prompt => "Year", 
                                            :start_year => Time.zone.now.year - 13, 
                                            :end_year => Time.zone.now.year - 80, 
                                            :field_name => :birth_year, 
                                            :prefix => :user }, 
                                            class:"form-control" %>
<% ... %>

it aught to be like this in rails:

<%= f.select_year :birth_year, { :prompt => "Year", 
                                            :start_year => Time.zone.now.year - 13, 
                                            :end_year => Time.zone.now.year - 80}, 
                                            class:"form-control" %>
like image 2
ajbraus Avatar answered Nov 14 '22 21:11

ajbraus