Forum: Ruby on Rails to_param vs to_query

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Miguel R. (Guest)
on 2009-03-12 19:21
(Received via mailing list)
to_param and to_query, what's the difference between those methods?
(Guest)
on 2009-03-12 20:25
(Received via mailing list)
On 12 Mar., 18:19, Miguel R. <removed_email_address@domain.invalid> 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 K.
http://twitter.com/rubyguy
(Guest)
on 2009-03-12 20:28
(Received via mailing list)
On 12 Mar., 19:25, "removed_email_address@domain.invalid" 
<removed_email_address@domain.invalid> wrote:
> On 12 Mar., 18:19, Miguel R. <removed_email_address@domain.invalid> wrote:

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

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
Andrew Chalkley (Guest)
on 2009-03-12 20:31
(Received via mailing list)
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 R. (Guest)
on 2009-03-13 11:23
(Received via mailing list)
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.
Miguel R. (Guest)
on 2009-03-23 13:25
(Received via mailing list)
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).
This topic is locked and can not be replied to.