Search code examples
ruby-on-railsselecttimeshort

Use short datetime in rails collection_select


This is a minor annoyance I can't find anything on.

I have a collection select on an Appointment object that shows the times of available appointments:

f.collection_select :appointment_id, @available, :id, :time, {:prompt => "Select a time"}

This displays using the standard DateTime format: 2011-10-31 08:00:00 UTC but I would really prefer the short format, like this:

appointment.time.to_s(:short)

which displays as 31 Oct 08:00

I can't seem to find the syntax when working with a symbol. Anybody know this?


Solution

  • [While there are hoops you could jump through if you want to maintain the purity of MVC (formatting a date probably isn't what a model should be worried about), I think this is simple enough to be OK.]

    Add a method to your model that gives you the string that you want to see.

    def short_time
      time.to_s(:short)
    end
    

    Then use :short_time as your text_method symbol in collection_select.