如何在提交时对 Viralheat 进行 API 调用,然后解析并保存 JSON 响应?
我想在控制器的更新方法中通过 Viralheat 的 API 发送请求,以便当用户点击提交按钮时,操作完成并进行 API 调用。我想发布到 http://www.viralheat.com/api/sentiment/review.json?text=i&do¬&like&this&api_key=[* 你的 api 密钥 * ]
这将返回一些以下格式的 JSON:
{"mood":"negative","prob":0.773171679917001,"text":"i do not like this"}
是否可以在执行控制器方法时同时进行 API 调用以及如何处理 JSON 响应?我应该将其放入哪种控制器方法中?
最终,我想将响应情绪保存到 BrandUsers 表中的情绪列中。提交位于 main.html.erb 中,然后使用 update 方法。
控制器
def update
@brand = Brand.find(params[:id])
current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)
if @brand.update_attributes(params[:brand])
redirect_to :root, :notice => "Brand tagged."
else
render :action => 'edit'
end
end
def main
@brands = Brand.all
if current_user
@brand = current_user.brands.not_tagged_by_user(current_user).order("RANDOM()").first
end
I want to send a request via Viralheat's API in my controller's update method so that when a user hits the submit button, an action is completed and the API call is made. I want to post to http://www.viralheat.com/api/sentiment/review.json?text=i&do¬&like&this&api_key=[* your api key *]
This will return some JSON in the format:
{"mood":"negative","prob":0.773171679917001,"text":"i do not like this"}
Is it possible to make that API call simultaneously while executing the controller method and how would I handle the JSON response? Which controller method would I put it in?
Ultimately I'd like to save the response mood to my sentiment column in a BrandUsers table. Submit is in main.html.erb which then uses the update method.
Controller
def update
@brand = Brand.find(params[:id])
current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)
if @brand.update_attributes(params[:brand])
redirect_to :root, :notice => "Brand tagged."
else
render :action => 'edit'
end
end
def main
@brands = Brand.all
if current_user
@brand = current_user.brands.not_tagged_by_user(current_user).order("RANDOM()").first
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
安装了
wrest
gem 后,您可以执行类似response
的操作,其中包含已转换为哈希值的 json。这样您就可以通过以下方式访问心情With the
wrest
gem installed, you could do something likeresponse
would contain the json already turned into a hash. So you can access the mood with