Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.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 来自其他域的Rails JSON数据?_Ruby On Rails_Ruby_Json - Fatal编程技术网

Ruby on rails 来自其他域的Rails JSON数据?

Ruby on rails 来自其他域的Rails JSON数据?,ruby-on-rails,ruby,json,Ruby On Rails,Ruby,Json,我正在尝试从其他域获取JSON数据。我使用了以下代码: class EMPInfoController < ApplicationController require 'httparty' def empdata uri = HTTParty.get("http://www.somesite.com/jsondata/xyz") resp = JSON.parse(uri.body) @empdata = resp end end 我可以简单地将它移动到@EmpDa

我正在尝试从其他域获取JSON数据。我使用了以下代码:

class EMPInfoController < ApplicationController
require 'httparty'

 def empdata 
  uri = HTTParty.get("http://www.somesite.com/jsondata/xyz")
  resp = JSON.parse(uri.body)
  @empdata = resp
 end

end
我可以简单地将它移动到
@EmpData
并使用
@EmpData[:first\u name]
在以后的视图中检索它吗


我是Rails新手,在项目的每一步都需要一些指导

将JSON数据包装在Ruby类中,并将其作为
app/models/JSON_data.rb

class JsonData
  attr_reader :emp

  def initialize(attributes)
   @emp = attributes[:emp]
  end

  def self.from_json(json_string)
    parsed = JSON.parse(json_string)
    emp = Emp.new(parsed['empid123456'])
    new(:emp => emp)
  end
end
class Emp
  include ActiveModel::Serializers::JSON
  include ActiveModel::Validations
  ATTRIBUTES =  [:first_name, :last_name, :title, :age, :blood_group]
  attr_accessor *ATTRIBUTES
   ###add your activemodel validations here ###

  def initialize(attributes = {})
    self.attributes = attributes
  end

  def attributes
    ATTRIBUTES.inject(
    ActiveSupport::HashWithIndifferentAccess.new
    ) do |result, key|
      result[key] = read_attribute_for_validation(key)
      result
    end
  end

  def attributes= (attrs)
    attrs.each_pair {|k, v| send("#{k}=", v)}
  end

  def read_attribute_for_validation(key)
    send(key)
  end
end
emp
创建一个活动模型类,并将其放置在
app/models/emp.rb
中:

class JsonData
  attr_reader :emp

  def initialize(attributes)
   @emp = attributes[:emp]
  end

  def self.from_json(json_string)
    parsed = JSON.parse(json_string)
    emp = Emp.new(parsed['empid123456'])
    new(:emp => emp)
  end
end
class Emp
  include ActiveModel::Serializers::JSON
  include ActiveModel::Validations
  ATTRIBUTES =  [:first_name, :last_name, :title, :age, :blood_group]
  attr_accessor *ATTRIBUTES
   ###add your activemodel validations here ###

  def initialize(attributes = {})
    self.attributes = attributes
  end

  def attributes
    ATTRIBUTES.inject(
    ActiveSupport::HashWithIndifferentAccess.new
    ) do |result, key|
      result[key] = read_attribute_for_validation(key)
      result
    end
  end

  def attributes= (attrs)
    attrs.each_pair {|k, v| send("#{k}=", v)}
  end

  def read_attribute_for_validation(key)
    send(key)
  end
end
在控制器中,您现在可以执行以下操作:

def empdata 
  uri = HTTParty.get("http://www.somesite.com/jsondata/xyz")
  @empdata = JsonData.from_json(uri.body)
end
在您看来,您可以使用:

@empdata.first_name
@empdata.last_name 

检索相应的值。

找到了解决方案。。谢谢@pette

@first_name = []
@last_name = []
@title = [] 
@age = []
@blood_group = []
thixjs = "#{emp}.json"
resp.each do |key_category, group_category|
  group_category.each do |key,val|
    if group_category.is_a? Array
      eval("@#{key}") << val
    elsif group_category.is_a? Hash
      if key == thixjs
      else
        eval("@#{key}") << val
      end
    end
  end
end
@first\u name=[]
@姓氏=[]
@标题=[]
@年龄=[]
@血型=[]
thixjs=“#{emp}.json”
分别为每个do |键|类别、组|类别|
组|类别。每个do |键,val|
如果group_category.是_a?排列

eval(“@#{key}”)是
empid123456
键静态还是动态?或者你想写emp:{“id”:“123456”,…我真的不明白你的问题。你想知道,如何将JSON对象传递给客户端JavaScript吗?@pette-empid在我的实际问题中是动态的,它是基于param-query字符串调用的,但在上述情况下,我们假设它是动态的static@PeterSorowka-我需要帮助获取rails视图中的数据..我不是sure如果我们可以直接使用javascript与其他门户进行ajax调用,但是如果有任何其他方法可以在创建的json页面上使用javascript获取我的数据。请建议您希望服务器只返回json字符串还是需要将其嵌入模板中?在任何情况下,我认为您可以跳过在服务器端解析json文件直接输出
uri.body
(当然,除了任何错误处理)哇,这看起来太过分了。OP没有要求验证。为了实现后一点,构建一个OpenStruct对象就足够了…@pette-谢谢,但它一直给我命名错误(对于nil:NilClass,未定义的方法
new':app/models/json_data.rb:10:in
from_json'@Andy我已经在json_data.rb.和emp.rb.中编辑了代码,但是这只在empdata123456是静态的并且不随请求参数而改变的情况下才有效。@pette仍然无法让它工作。。现在它似乎在获取每个_对时都会中断。。我不确定是否正确。还有新的问题仍然存在..让我澄清..json数据来自其他域(非本地),如果它在
每个_对上断开
,这意味着json对象密钥与emp对象的属性不一致。请确保
empid123456
json对象中的所有密钥都在emp模型的
属性=[..]
行中。