Formatting Date and Datetime in Rails

It’s actually pretty easy, and even though the documentation references only show it with datetime, it also seems to work on date objects as well.

So here are the different formats:

 datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0)   # => Tue, 04 Dec 2007 00:00:00 +0000

  datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00"
  datetime.to_s(:db)                      # => "2007-12-04 00:00:00"
  datetime.to_s(:number)                  # => "20071204000000"
  datetime.to_formatted_s(:short)         # => "04 Dec 00:00"
  datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00"
  datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00"
  datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"

I used it on a date object with the :long format, and worked like a charm!

credit here

Pass a value through a link in Rails

I was trying to use the link_to method and it was giving an error

missing required keys: [:id]

I was trying to link_to a Supplier model from the PurchaseOrder index like this:

<%= link_to purchase_order.items[0].suppliers[0].name, supplier_path %></td>

Yes I know it looks convoluted – I have a somewhat complex database structure with several :has_many :through models that are nested and using accepts_nested_attributes_for

Anyway, I figured out via this Stack Overflow question that its actually quite easy to simply pass a value through the supplier_path like this:

supplier_path(:id => purchase_order.items[0].suppliers[0].id)

which gives my full link_to method as:

<%= link_to purchase_order.items[0].suppliers[0].name, supplier_path(:id => purchase_order.items[0].suppliers[0].id) %>

Don’t be confused by my convoluted code, essentially a simpler form would be:

<%= link_to, supplier_path(:id => purchase_order.suppliers[0].id) %>

Hope this is helpful!

The difference between link_to and mail_to in Ruby on Rails

Small difference, but important.  They are essentially reversed.  Since jonathan ng said it better than me, and I found this resource from his blog, I’m going to credit and link to his post from his Ruby on Rails blog:

Screen Shot 2013-12-04 at 9.23.08 PM