format a date in the rails model - ruby-on-rails-3

I have a date of birth in the rails model and I display it in different places. Every time I have to specifically format it in mm/dd/yyyy format. Is there something I can do in my model so that every time I get the dob out it comes in mm/dd/yyyy format.

You can define a quick formatted_birthday method in your model, but if you're just outputting this to views you can use Rails' built in date formatting output:
http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
time:
formats:
birthday: "%m/%d/%Y"
Then in your view just use:
<%= l person.birthday, :format => 'birthday' %>
Or you can change birthday to default in the format definition and you can omit the :format option all together.

Yes you can. In config/initializers/some_initializer.rb
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Now all your dates will always be out in the above format.
If you want to selectively choose it only sometimes. Then
Date::DATE_FORMATS[:myformat] = "%m/%d/%Y"
And then you can use whereever you like
your_date.to_s(:myformat)

Related

simple_form date not working after the 12th of each month

Has anyone run into this problem? I have a User object and a simple_form which asks for the User's birthday.
<%= f.input :birthday, as: :date, start_year: Date.today.year - 70,
end_year: Date.today.year, order: [:month, :day, :year], label: false %>
Any date I pick I can only pick a day up to the 12th of each month. If I pick 13th or higher simple_form says "Please enter a valid date". Very strange.
I got this code from https://github.com/plataformatec/simple_form and all it says about this code is "SimpleForm accepts same options as their corresponding input type helper in Rails". Does anyone know where the corresponding input type helper in Rails is documented?
I would guess that you've confused :day and :month somewhere.
Or maybe, put differently, you want to use the American format and instead you're using the european format (or the reverse). Not sure it will help, but see this link:
How can I use US-style dates in Rails using Ruby 1.9?

Rails field "can't be blank", even though it's not blank

I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.
views/dinners/new.html.erb:
<%= f.text_field :date, id: "datepicker" %>
models/dinner.rb:
attr_accessible :date
validates_presence_of :date
dinners_controller.rb:
def create
#dinner = Dinner.new params[:dinner]
if #dinner.save
flash[:notice] = "Dinner created successfully."
redirect_to controller: 'dinners'
else
flash.now[:alert] = #dinner.errors.full_messages.join("<br>").html_safe
render action: "new"
end
end
Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?
I've found the answer.
My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.
I chose the easy solution and changed the default date of datepicker, as shown here.
Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.

Date and Date Ranges in Rails 3

I have a Rails 3 application with a prescription model. The model has a number of fields, two of them are to calculate and display the duration of a prescription.
At the moment the user enters a value in a text field such as '3 Months' and then manually changes a datetime input to three months from now. This seems like a perfect form to automate for the user.
Currently the fields are like this:
Duration of Treatment
<%= f.text_field :duration, :class => "input-text" %>
Date of Expiry
<%= f.datetime_select :expiry, :order => [:day, :month, :year], :class => "input-text" %>
So, my question. How can I create two dropdown lists for the duration field such as:
[1] [Day]
The user can select the number from the first list and in the second they can choose Day, Week or Month.
The value they pick using the duration select boxes would be saved as a text string e.g. "1 month" and the value of the Time.now in 1 month would be saved as a datetime value in the expiry column.
Is something like this possible to do? If so, how?
I'll provide an example of how you'd use the chronic gem, since it seems tailor-made for this purpose:
require 'chronic'
duration = "3 months" # => "3 months"
Time.now # => 2012-07-09 18:43:50 -0700
Chronic.parse(duration + " from now") # => 2012-10-09 18:43:55 -0700
If I understand your use case correctly, you can then just get rid of the datetime select entirely. Ask the user for the text duration and assign that to the text attribute. Then use chronic to determine the time value from the text parameter and assign that to the datetime attribute. For extra credit get the parsed time value asynchronously and display it on the page before they submit the form so they can see that what they are submitting makes sense.
You can just do something easy like:
Time.now + 10.days
Source: How to add 10 days to current time in Rails
And how to do drop-downs?
Drop down box in Rails
Assuming the prescription is valid at the time of object creation, you can store the start date in the database as the current time Time.now (may want to convert to a datetime) and then based on the drop-down, add the amount of time until it expires like off the top of my head:
eval "Time.now + #{params[:prescription][:amount].#{params[:prescription][:time_type]}"
Hope that made sense. I would look up a better way to add the time though that maybe doesn't use eval. Heres the time reference: http://api.rubyonrails.org/classes/Time.html
First, change your duration field to a select menu with 1-30, or whatever numbers you want.
Then in the controller action that handles your form:
#prescription = Prescription.new(params[:prescrption])
#prescription.duration = "#{pluralize(params[:prescription][:duration], params[:prescription][:expiry])}"
if params[:prescription][:expiry] == "Day"
#prescription.expiry = Time.now + params[:prescription][:duration].days
elsif params[:prescription][:expiry] == "Week"
# Put week logic here
elsif params[:prescription][:expiry] == "Month"
# Put month logic here
end
# Put the rest of the #prescription.save stuff here.
It's a little verbose, but I think that's kind of the way it is with the way time is set up in Ruby...

Datepicker ui with formtastic, rails 3.1

I use rails 3.1, formtastic 2.0.2 and datepicker ui
I made datepicker_input.rb:
class DatepickerInput < Formtastic::Inputs::StringInput
include Formtastic::Inputs::Base
def input_html_options
super.merge(:class => "datepicker")
end
end
In application.js I wrote:
$('input.datepicker').datepicker()
I use it in my form like :as => :datepicker. I see calendar, pick date and everything is fine except for it doesn't fill column in my model. The only thing that I noticed is that when I fill first date and then all the other fields - it works. When date field is the last - it doesn't work. There is no errors, params[:model_name][:date_field] is not empty just nil in place of date that I chose.
Error was in date format - database just couldn't take format that returned datepicker.

Change date format in the view to dd/mm/yyyy

The default date format in Ruby is yyyy-mm-dd, but I needed them to be dd/mm/yyyy in the view
I have wrote a date_format file in config/initializers as:
Time::DATE_FORMATS.merge!( :uk_format => '%m/%d/%Y')
This didn't work since I need to call date.to_s(:uk_format) in order to use this format. But since I'm using <%= f.text_field :paymentDate %> to display the date, I'm not sure I can add to_s to this case.
Can someone help me out please.
Edit 1
Actually date.to_s(:uk_format) doesn't work either, how do I use initializer properly.....?
See: Change default Ruby Time format
Adapted my answer linked to above for the Date and format specified:
Since you're using Rails, take advantage of the I18n support: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
date:
formats:
default: "%d/%m/%Y"
Then you can call I18n.l Date.today to get out a formatted date. Or in your view, you can use <%= l #foo.created_at %>.
Try this instead:
Time::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})
Date::DATE_FORMATS.merge!({:db => '%m/%d/%Y', :uk_format => '%m/%d/%Y'})