Reputation: 1923
I have the following link_to
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=starting&daddr=ending&hl=en'
I want to replace the starting and ending with ruby syntax, location.start and location.end
I've tried
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=' + location.start+ '&daddr=' + location.end + '&hl=en'
but that does not seem to work. What is the best way to do this?
Edit: After playing around, it appears that although location.start and location.end are strings in the database, they are not when I try to add them on to other strings. In order to do so, Im must explicitly specify .to_string to both location.start and location.end
However, when I do this, the strings no longer appears on the show page. What is going on here?
Upvotes: 0
Views: 134
Reputation: 1161
If you are getting "no implicit conversion of nil into String" error, it means that your location.start or location.end is nil. So you should add a conditional check:
- if location.start.present? & location.end.present?
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=' + location.start+ '&daddr=' + location.end + '&hl=en'
- elsif !location.start.present? & location.end.present?
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=defaultstart' + '&daddr=' + location.end + '&hl=en'
- else
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=defaultstart&daddr=defaultend&hl=en'
Where defaultstart and defaultend can be replaced by default values.
Upvotes: 1
Reputation: 8831
You can use to_params
method.
params = {"saddr" => "starting", "daddr" => "ending", "hl" => "en"}.to_param
=> "daddr=ending&hl=en&saddr=starting"
url = 'http://maps.google.com/maps?' + params
=> "http://maps.google.com/maps?daddr=ending&hl=en&saddr=starting"
or use uri.
require 'uri'
uri = URI.parse('http://maps.google.com/maps')
uri.query = URI.encode_www_form("saddr" => "starting", "daddr" => "ending", "hl" => "en")
#uri.query = URI.encode_www_form("saddr" => "#{location.start}", "daddr" => "#{location.end}", "hl" => "en")
=> "saddr=starting&daddr=ending&hl=en"
uri.to_s
=> "http://maps.google.com/maps?saddr=starting&daddr=ending&hl=en"
Upvotes: 0
Reputation: 1223
You can use string interpolation:
= link_to 'Get Driving Directions!', "http://maps.google.com/maps?saddr=#{location.start}&daddr=#{location.end}&hl=en"
Note that I've used "
(quotes) instead of '
(single quotes) when using string interpolation otherwise it won't work.
Upvotes: 0