Rails 3 date_select for year only

I have a form in my Rails 3 application where I want to create a select tag in just a year using the method :grad_year . I have everything I need - and store - correctly using date_select and adding :discard_month and :discard_day . However, when I show @profile.grad_year , I get the month and day values. So I'm wondering how to store and display 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 
+6
source share
3 answers

Rails has a select_year :

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

So your code should look like this:

 f.select_year(Date.today, :start_year => Time.now.year, :end_year => Time.now.year - 95, :field_name => 'grad_year') 
+11
source

Gathering all of the above from @alex_peattie's answer, I came to the following:

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

As in the OP question, my case was executed in the form_for block, so f.select_year exception. But if you just use the documented option :field_name , the tag will have the identifier date_grad_year and the name date[grad_year] , which are not what Rails expects. Usage (only documented at the very top of the API) :prefix changes date to profile .

So, this is better than # @% $ ^ * & html_options hash, which, despite using rails for 5 years, I can’t get right without five attempts :-).

Oh, rails, how I love you, but at the same time, I'm glad that the qaru around us helps everyone understand your delightful features!

+5
source

This select_year function is completely screwed.

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" %> <% ... %> 

In rails should be like this:

 <%= f.select_year :birth_year, { :prompt => "Year", :start_year => Time.zone.now.year - 13, :end_year => Time.zone.now.year - 80}, class:"form-control" %> 
+2
source

Source: https://habr.com/ru/post/902022/


All Articles