to_formatted_s(format = :default) public

Converts a collection of elements into a formatted string by calling to_s on all elements and joining them. Having this model:

class Blog < ActiveRecord::Base
  def to_s
    title
  end
end

Blog.all.map(&:title) #=> ["First Post", "Second Post", "Third post"]

to_formatted_s shows us:

Blog.all.to_formatted_s # => "First PostSecond PostThird Post"

Adding in the :db argument as the format yields a comma separated id list:

Blog.all.to_formatted_s(:db) # => "1,2,3"
Show source
Register or log in to add new notes.
May 26, 2011
0 thanks

Don't Use to_formatted_s(:db) on an Array of IDs

I thought using to_formatted_s(:db) on an array of ids would separate them with commas in a nice way. Wrong. It does, but it also changes the numbers.

Wrong

[60, 271, 280, 283].to_formatted_s(:db)
# => "121,543,561,567"    # Completely different numbers!

Instead, use the join method:

Right

[60, 271, 280, 283].join(",")
# => "60,271,280,283"      # Much better

I think this has to do with (:db) being used for formatting dates but I’m not sure.

June 23, 2011
0 thanks

RE: Don't Use to_formatted_s(:db) on an Array of IDs

The reason it doesnt work @joshuapinter for IDs is because if you look at the source:

case format
  when :db
    if respond_to?(:empty?) && self.empty?
      "null"
    else
      collect { |element| element.id }.join(",") # look at this line
    end
  else
    to_default_s
end

It maps/collects the object ids and then joins them using a comma ; so in the case of 60 for instance :

60.object_id #=> 121

60.id #=> 121