我正在Rails应用程序中集成SMS API。从用户表中获取数字时,我收到的错误为:
TypeError (no implicit conversion of nil into String):
app/models/message.rb:16:in `+'
app/models/message.rb:16:in `sms_message'
这是我的message.rb
def sms_message
require "rubygems"
require "net/https"
require "uri"
require "json"
uname = "demo@gmail.com"
hash = "54030737b105dsds7777 "
numbers = numbers
message = body
sender = "TXTLCL"
requested_url = 'http://api.textlocal.in/send/?' + "username=" + uname + "&hash=" + hash + "&numbers=" + numbers + "&message=" + body + "&sender=" + sender
uri = URI.parse(requested_url)
http = Net::HTTP.start(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
res = http.request(request)
response = JSON.parse(res.body)
puts (response)
end
def message_number
numbers = Student.new do |u|
u.phone1 = numbers
end
end
答案 0 :(得分:1)
Rails有一个很好的方法叫做to_query。 首先,像这样构建一个params哈希:
params = {username: uname, hash: hash, numbers: numbers, message: body, sender: sender}
然后,只需致电"http://api.textlocal.in/send/?#{params.to_query}"
params.to_query
将处理零值。
但是,这只是编写代码的好方法。如果值为nil,您仍会得到相同的错误。最好是在进行API调用之前添加一些验证。此外,请确保您是否发送了API所期望的确切密钥。
答案 1 :(得分:0)
您的numbers
或body
为nil
要避免这种情况,您可以将这些值转换为字符串或使用插值
转换为字符串
numbers = numbers.to_s
message = body.to_s # Use message instead of body while joining using +
requested_url =
'http://api.textlocal.in/send/?' + "username=" + uname + "&hash=" + hash +
"&numbers=" + numbers + "&message=" + message + "&sender=" + sender
使用插值
requested_url =
"http://api.textlocal.in/send/?username=#{uname}&hash=#{hash}&numbers=#{numbers}&message=#{message}&sender=#{sender}"