我有以下link_to
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=starting&daddr=ending&hl=en'
我想用ruby语法替换起始和结尾, location.start 和 location.end
我试过
= link_to 'Get Driving Directions!', 'http://maps.google.com/maps?saddr=' + location.start+ '&daddr=' + location.end + '&hl=en'
但这似乎不起作用。这样做的最佳方式是什么?
编辑:玩完之后,虽然 location.start 和 location.end 是数据库中的字符串,但是当我尝试添加它们时,它们不会出现到其他字符串。为了做到这一点,我必须明确指定 .to_string location.start 和 location.end
然而,当我这样做时,字符串不再出现在节目页面上。这是怎么回事?
答案 0 :(得分:1)
如果您收到“没有将nil隐式转换为String”错误,则表示您的location.start或location.end为nil。所以你应该添加一个条件检查:
- 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'
默认值可以替换defaultstart和defaultend。
答案 1 :(得分:0)
您可以使用字符串插值:
= link_to 'Get Driving Directions!', "http://maps.google.com/maps?saddr=#{location.start}&daddr=#{location.end}&hl=en"
请注意,在使用字符串插值时,我使用了"
(引号)而不是'
(单引号),否则它将无效。
答案 2 :(得分:0)
您可以使用to_params
方法。
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"
或使用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"