to_param vs to_query

55 views
Skip to first unread message

Miguel Regedor

unread,
Mar 12, 2009, 1:19:54 PM3/12/09
to Ruby on Rails: Talk
to_param and to_query, what's the difference between those methods?

rub...@ymail.com

unread,
Mar 12, 2009, 2:25:01 PM3/12/09
to Ruby on Rails: Talk
On 12 Mar., 18:19, Miguel Regedor <miguelrege...@gmail.com> wrote:
> to_param and to_query, what's the difference between those methods?

If you are refering to the Array class which has been extended with
the two methods #to_param and #to_query, I can tell you that #to_param
calls #to_param calls on all its contained elements and joins them
with a slash. In contrast #to_query calls #to_query on all contained
elements, prefixes them with the first argument ('key') plus [] and
joins it all with an ampersand.

['hello', 'great', 'world'].to_param # => hello/great/world
['hello', 'great', 'world'].to_query('words') # => words%5B
%5D=hello&words%5B%5D=great&words%5B%5D=world

#to_param is used after the question mark in a URI, #to_query after.
Hope it makes things clear. :)

--
Cheers,
David Knorr
http://twitter.com/rubyguy

rub...@ymail.com

unread,
Mar 12, 2009, 2:27:57 PM3/12/09
to Ruby on Rails: Talk
No, I meant: "#to_param is used BEFORE the question mark in a URI,
#to_query after." Like this: hello/great/world?words%5B%5D=hello&words
%5B%5D=great&words%5B%5D=world

Andrew Chalkley

unread,
Mar 12, 2009, 2:30:47 PM3/12/09
to Ruby on Rails: Talk
to_param returns the id by default (this is used in the
url /:controller/:action/:id) whereas to_query takes an argument (the
parameter key) object_instance.to_query "o" returns the "o=:id" for
using at the end of urls - custom/'non-restful' actions but
referencing that object.

Miguel Regedor

unread,
Mar 13, 2009, 5:23:03 AM3/13/09
to Ruby on Rails: Talk
Thanks to both for the clarification, I was already guessing that
to_query was the correct choice for my scenario, but now I'm much more
confidant!

cheers
Miguel Regedor

Miguel Regedor

unread,
Mar 23, 2009, 7:24:00 AM3/23/09
to Ruby on Rails: Talk
I noticed a funny thing, while doing this. We can not use it with an
Hash inside an array because the Hash elements will be spread all over
the array thanks to URL query brackets syntax for Arrays(if the array
index was specified in this syntax it would work, but I don't think
there is way to get to_query doing it I think the best way is to use
only Hashes instead).
Reply all
Reply to author
Forward
0 new messages