views:

157

answers:

3

Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it.

t.column :year, ???

Would this year be best represented as an integer, date, or datetime?

A: 

Well, if you only care about the year, an integer will do just right. If you're not certain that you will never, ever, need month and day, then date, and if you also may need the hour/minute/second, then datetime, but if you need a datetime, it should not be called year :-)

mat
+3  A: 

I suggest using integer. Both Date and DateTime have more precision than you want, which could be misleading. Even if you initialize them w/only a year, they will store a default month and day (Jan, 1). For example, if you used Date, your output would look like this:

>> m = YourModel.create(:year => '2008')

>> m.year.to_s
=> "2008-01-01"

If you use integer you get what you'd expect:

>> m = YourModel.create(:year => '2008')

>> m.year.to_s
=> "2008"
Gordon Wilson
But you can use simple format helpers to display the year only. Plus you receive helpers from the Date module for comparisons and such. And if you ever need to do store day/month, it won't require a major schema modification.
mwilliams
I do not know who down voted you, but I up vote you, Using an Integer is excellent if you require only Year. If you want more detail, using Date. That's it. Nice call Gordon.
Daok
+7  A: 

I would recommend just going with Rails conventions and doing a Date data type. This way, if you ever do need the month and day, you can retrieve it. Plus, it's simple to do:

YourModel.date.year  # => "1999"
Josh