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.

4
  • Are you saving the date as as a string or date in the database? Commented Sep 14, 2013 at 6:06
  • 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? Commented Sep 14, 2013 at 6:08
  • 1
    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 Commented Sep 14, 2013 at 6:24
  • 1
    Saving as a date in Postgres Commented Sep 14, 2013 at 10:00

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's saved as date in PostgreSQL
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"
)

1 Comment

environment.rb:7:in `<top (required)>': uninitialized constant ActiveSupport::CoreExtensions (NameError)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.