Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 轨道形式=>;URL=>;JSON=>;保存参数_Ruby On Rails_Ruby_Ajax_Json_Post - Fatal编程技术网

Ruby on rails 轨道形式=>;URL=>;JSON=>;保存参数

Ruby on rails 轨道形式=>;URL=>;JSON=>;保存参数,ruby-on-rails,ruby,ajax,json,post,Ruby On Rails,Ruby,Ajax,Json,Post,这基本上就是我想要做的,通过表单中的参数,我想要对一个站点执行GET/POST请求,这个站点需要一个特定的URL,比如,它会给我一个JSON,我想要在提交表单时解析/保存来自这个JSON的数据到我的rails应用程序中 我完全迷恋这种方式,任何事情都将非常感激 Rails Form Data=>Build the URL=>Do a GET/Post request=>Catch JSON=>Parse=>Save我想你是想请求另一个站点而不是你的站点来获得响应。因此,您可以安装curb gem

这基本上就是我想要做的,通过表单中的参数,我想要对一个站点执行GET/POST请求,这个站点需要一个特定的URL,比如,它会给我一个JSON,我想要在提交表单时解析/保存来自这个JSON的数据到我的rails应用程序中

我完全迷恋这种方式,任何事情都将非常感激


Rails Form Data=>Build the URL=>Do a GET/Post request=>Catch JSON=>Parse=>Save

我想你是想请求另一个站点而不是你的站点来获得响应。因此,您可以安装curb gem(ruby中的curl包装器)。然后使用它在另一个站点上发出请求,并使用标准RoR工具(如json)解析json以进行哈希。

对于rest api,您可以在应用程序中使用activeresource

如果是非常特定的内容,您可以使用Net::Http发出请求,然后自己将json解析为ruby对象

使用示例

对于解码json,您可以使用 Json或ActiveSupport::Json.decode或此

从您获得的,您可以执行以下操作:

在文件顶部添加:

require "net/http"
require "uri"
require 'json'
然后在控制器或助手中:

#set the uri
uri = URI.parse("http://my.site.com/uri")

#set the post params and get the respons
response = Net::HTTP.post_form(uri, {"first_param" => "my param", "second_param" => "another param"})

#get the json info
data = JSON.parse(response.body)

#set result to an ActiveRecord (maybe there is a better way to do this, I guess it depends on the response you get
@something = Mymodel.new
@something.name = data["name"]
...
@something.save
希望有帮助