rails, how to get params from url string?
19,418
Solution 1
It might be done using some regexp for example
irb(main):011:0> s = "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
=> "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
irb(main):012:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,1]
=> "28"
irb(main):013:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,2]
=> "142"
irb(main):014:0> s[/.*\/(\d+).+x=(\d+).*y=(\d+)/,3]
=> "142"
irb(main):015:0>
Solution 2
The correct approach :
url = "http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142"
uri = URI::parse(url)
id = uri.path.split('/')[4]
params = CGI::parse(uri.query)
Solution 3
In your controller you can do 'params[:x]' and 'params[:y]'. For example:
x = params[:x]
y = params[:y]
Comments
-
el_quick almost 2 years
Possible Duplicate:
How do I easily parse a URL with parameters in a Rails test?sorry for my english...
I have in my archives.rb model a method to get all src attributes from a html content, I am getting src's like:
http://localhost:3000/es/editor/archives/28/show_image?x=142&y=142
I need to get the params from that url, specifically: id, x, y
Thanks, Regards.
-
el_quick over 12 yearsthanks, but ... I can't do that, first: my code is in a model, and second the url's are string extracted from html text code.
-
Marc-André Lafortune over 12 yearsThere are so many ways this could fail. Let's not use flaky Regex when robust parsers already exist.
-
DGM over 12 yearssuch a poor answer, use CGI parse as explained in the dup answer link.
-
Bohdan over 12 yearsyou forgot about an
id
-
DGM over 12 yearsupdated to get the id then. :)
-
DGM over 8 yearsedit was wrong, and the suggested edit to fix it was incorrectly rejected. I have corrected it.
-
Bohdan over 7 yearsI disagree that my answer is poor and DGM's one is correct since both approaches depend on a structure of the url, mine to get all three params and DGM's to get and id. Both will fail if the url is different. I do agree that using CGI to get x and y values looks pretty.