3
votes

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.

3
Are you saving the date as as a string or date in the database? - Zero Fiber
When you say 'didn't do the job', you mean it didn't work as expected or was there an error? If so, what was the error? - Rajesh Kolappakam
In any case, instead of adding the date formatting code in your model, you should consider using draper or any other presentation layer concept. railscasts.com/episodes/286-draper - Rajesh Kolappakam
Saving as a date in Postgres - Jackie Chan

3 Answers

1
votes

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.

0
votes

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"
)
0
votes

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