3

I am using Ruby On Rails 4 and twitter-bootstrap-rails, to the client wants to dislay dates in this format:

14 September 2013 Well pretty cool, there we go:


    var start = $("#project_start_date").datepicker({
        format: 'dd MM yyyy',
        autoclose: true
    })

However when the date is saved to the database it is saved as "2013-09-14". Well cool, however when I want to edit the page I see the following:

2013-09-14 as the output of the field :( Not good hey.

So how would you output the date in a given format (I probably need @start_date.stftime("%d %B %Y").

Just wanted to say, that:

  1. getter methods didn't do the job: def start_date() @start_date.stftime("%d %B %Y") end
  2. before_validation also didn't do:
 
before_validation :date_validation

  def date_validation
    @start_date = self.start_date.strftime("%D %m %Y")
    @end_date =   self.end_date.strftime("%d %m %Y")
  end

PS I am using Postgres.

Jackie Chan
  • 2,654
  • 6
  • 35
  • 70

3 Answers3

1

Check whether the date is being stored as a string in the database as thats what it seems.

Try generating a migration and making sure you have a date column, something like this

def change    
   change_column :table_name, :start_date, :datetime
   change_column :table_name, :end_date, :datetime
end

That way, you can then use strftime to format it as you mentioned above.

derekyau
  • 2,936
  • 1
  • 15
  • 14
0

To change the format in which the date is saved in the database, add this piece of code to the environment.rb file.

# environment.rb :

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
     :default => "%d %B %Y"
)
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
0

I decided to make this old Q complete by answering it.

Aside from using draper that was mentioned in a comment, the easiest way is to override AR getter, not in a validation, i.e.

# in your model
def start_date
  self[:start_date].strftime("%D %m %Y")
end
Community
  • 1
  • 1
mlt
  • 1,595
  • 2
  • 21
  • 52