Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing a year with RoR?

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?

like image 775
speciousfool Avatar asked Dec 06 '22 07:12

speciousfool


2 Answers

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"
like image 114
Gordon Wilson Avatar answered Dec 21 '22 07:12

Gordon Wilson


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"
like image 32
Josh Delsman Avatar answered Dec 21 '22 07:12

Josh Delsman