【问题标题】:Associate current_user with json response from API call in Rails将 current_user 与 Rails 中 API 调用的 json 响应相关联
【发布时间】:2015-07-10 07:30:49
【问题描述】:

我需要将当前用户与我在 PostgreSql 9.4 中捕获和存储的 json 响应联系起来。我正在使用 Rails 4。我能够成功地将 json 存储在 json 数据类型的“return”列中。我已采取措施创建模型关联并更新了架构,并且我有一个带有记录的用户模型,但 user_id 在包含 json 返回的文档记录中仍然为零。我列出了控制器,因为我几乎确信我的问题就在这里。

require 'alchemyAPI/alchemyapi'
require 'json'

class AlchemyController < ApplicationController

def index
  @documents = Document.all
end

def create
  alchemyapi = AlchemyAPI.new()
  response = alchemyapi.combined('url', params[:q],  {'extract'=>'page-image, title, author, concept' })
  puts JSON.pretty_generate(response)

if 
  Document.create(result: response)
  flash[:notice] = "Input was successfully analyzed and persisted."
  redirect_to action: 'index'
else
  flash[:notice] = "Input was successfully analyzed and persisted."
  redirect_to action: 'index'
end
end
end

【问题讨论】:

  • 如果您删除了对您在标题中提到的问题的引用,这个问题仍然有效吗?
  • 我知道如何以从表单传入参数的标准方式使用创建控制器操作。我不知道该怎么做是将这些参数替换为我从 API 返回的 json。

标签: ruby-on-rails ruby json postgresql controller


【解决方案1】:

我的解决方案是添加当前用户,如 if 块的前两行所示。

def create
 alchemyapi = AlchemyAPI.new()
 response = alchemyapi.combined('url', params[:q],  {'extract'=>'page-image, title, author, concept' })
 puts JSON.pretty_generate(response)

if 
 *@user = current_user*
 *@user.documents.create(result: response)*
 flash[:notice] = "Input was successfully analyzed and persisted."
 redirect_to action: 'index'
else
 flash[:error] = "There was a problem analyzing your input."
 redirect_to action: 'index'
end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 2012-03-06
    • 2017-06-03
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多