Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store year in Rails app

I want to just store the year in one of my models. At the moment I just have a database field called year of type date, but it seems to want to take a whole date (yyyy-mm-dd) rather than just a year.

What's the best way to store this? In a date field but using some way of just getting it to store the date bit (in which case, how?), or in an int field, or a string field or what? In some ways using an int field feels wrong, but it might be the easiest.

like image 726
robintw Avatar asked Oct 14 '08 18:10

robintw


2 Answers

It depends on the range of dates that are possible. If your dates go from BC to far future (negative to more then 4 digits), it would be easiest to store an integer (just for sorting reasons). This is also true if you want to make calculations or compare dates.

Otherwise I would probably go with a string.

Using a date field use January 1st and extract the year part when showing.

like image 162
Ralph M. Rickenbach Avatar answered Oct 20 '22 10:10

Ralph M. Rickenbach


I'd advise against using an arbitrary chosen date in a date field on the basis of maintainability. You will know you have arbitrarily chosen this but will subsequent maintainers of your app?

I'd go with an int because that way you are not storing anything other than what you mean to store and there can't be much confusion about the meaning of it.

like image 33
srboisvert Avatar answered Oct 20 '22 10:10

srboisvert