To_param vs to_query

to_param and to_query, what’s the difference between those methods?

On 12 Mar., 18:19, Miguel R. [email protected] 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. :slight_smile:


Cheers,
David K.
http://twitter.com/rubyguy

On 12 Mar., 19:25, “[email protected][email protected] wrote:

On 12 Mar., 18:19, Miguel R. [email protected] wrote:

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

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


Cheers,
David K.
http://twitter.com/rubyguy

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 R.

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.

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).