to_formatted_s
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (-2)
- 3.1.0 (-2)
- 3.2.1 (-2)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (24)
- 4.1.8 (-38)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (11)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (5)
- 7.1.3.2 (-35)
- 7.1.3.4 (0)
- What's this?
to_formatted_s(format = :default)
public
Extends Array#to_s to convert a collection of elements into a comma separated id list if :db argument is given as the format.
This method is aliased to to_fs.
Blog.all.to_formatted_s(:db) # => "1,2,3" Blog.none.to_formatted_s(:db) # => "null" [1,2].to_formatted_s # => "[1, 2]"
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.
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