ruby-on-rails - 在 Rails 中从 REST 获取 Post 数据

标签 ruby-on-rails ruby json post rails-routing

这是一个很长的问题,如果需要一段时间才能理解,我深表歉意。我会尽量保持简单。

我在这里开始有点绝望,但我已经很接近了。我一直在与 Ruby 斗争一段时间,并与 post 和 net::http 进行通信。所以我现在得到的是一个散列被转换成 json。使用来自 net::http 的 post 请求通过网络发送,然后我试图将它变回一个对象。

我探索过的一条路线是事件记录和事件资源,但在双方都遇到一些问题后,我决定定义我自己的模型,然后找出如何转换和发送它。

我的模型

此模型称为 customRequest。在其中,我有一个 post_me,它将 2 个类变量转换为散列,将其转换为 json,然后发送。

class CustomRequest
  require 'json'
  require 'net/http'
  attr_accessor :myString, :myInteger

  def initialize(myString,myInteger)
    @myString = myString
    @myInteger = myInteger
  end

  def post_me

    @myReq = {:myString => @myString, :myInteger =>@myInteger}
    myJsonReq = @myReq.to_json
    #myJsonReq = JSON.generate(@myReq)
    puts myJsonReq
    #    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add'),
    #    myJsonReq)

    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add.json'),
    myJsonReq).as_json
  end
end

简而言之,这就是自定义请求。

问题

我关心的是:

  1. 接收 URL,我写了 add.json,因为格式是在 Controller 路由中确定的。不知道有没有必要?
  2. 是从变量生成散列并将其发送以进行重建更好,还是将整个类转换为_json 并发送更好?

如果我按原样在 Rails 控制台中创建类并发送它,我会在终端中收到一个不错的 200 和一个响应。

更多详情

(注意:如果你真的想知道场景中发生了什么,请只阅读这一点)

@test.post_me
{"myInteger":300,"myString":"testestest"}
=> {"x-ua-compatible"=>["IE=Edge"], "etag"=>["\"d41d8cd98f00b204e9800998ecf8427e\""], "connection"=>["Keep-Alive"], "content-type"=>["application/json; charset=utf-8"], "date"=>["Thu, 14 Jul 2011 15:54:24 GMT"], "server"=>["WEBrick/1.3.1 (Ruby/1.8.7/2009-06-12)"], "x-runtime"=>["0.022517"], "content-length"=>["0"], "set-cookie"=>["_webApp_session=BAh7BiIPc2Vzc2lvbl9pZCIlZTJmM2IwYmVhZWMwM2E2ZGQzNWEwMDUwNmE2NDhlM2U%3D--5312eec4795d9f0633520c01992422e9c15746e4; path=/; HttpOnly"], "cache-control"=>["max-age=0, private, must-revalidate"]}
>> 

如果我不将其转换为 Json,这是相同的响应:

{"myInteger":300,"myString":"testestest"}
=> #<Net::HTTPOK 200 OK  readbody=true>

如果有人能回答问题 1 和 2,我将不胜感激


服务器端

这里是服务器端,需要接收请求并将其转回 Json 和一个对象。我尝试了很多不同的东西,但大多数都被注释掉了。

基本上我会得到一个 200 响应,其中包含标签中的详细信息,但是当我尝试放置哈希对象时,我什么也得不到/

Started POST "/user_requests/add" for 127.0.0.1 at Thu Jul 14 16:56:07 +0100 2011
  Processing by UserRequestsController#add_request as 
  Parameters: {"{\"myInteger\":300,\"myString\":\"testestest\"}"=>""}
Rendered user_requests/add_request.json.erb (0.3ms)
Completed 200 OK in 31ms (Views: 27.4ms | ActiveRecord: 0.0ms)

这是将其分解并将其变回对象的多次尝试。

  def add_request
    require 'rubygems'
    require 'json'

    #@custom = CustomRequest.new(params[:custom]) 
    #@custom = CustomRequest.new(JSON.parse(params[:custom]))
    #@custom = CustomRequest.new(params[:custom]).from_json
    #@custom = CustomRequest.new(params[:custom].from_json) 


     @myHash = Hash.new(params[:myHash])
     #@myHash = Hash.new(JSON.parse(params[:myHash]))
    #@myHash = Hash.new(params[:myHash]).from_json
    #@myHash = Hash.new(params[:myHash].from_json) 


     puts "IT WORKS!"
     puts @myHash.to_s

它们几乎都一样,除了一个是我试图从发送的哈希重新创建对象,另一个是我试图重新创建 hash_to_json 到 hash_from_json

更多问题

所以:

  1. 我是否使用 params(:myHash) 正确地创建了对象,还是应该单独引用每个变量?
  2. 参数是自动转换回可读格式还是我需要从 JSON 中输入或解析 JSON。就此而言,我使用哪个重要吗?
  3. 我是否正确重建了对象,为什么我的 has 没有显示任何内容?
  4. (可选)此后是否有任何简单的方法将其存储在表中?

最佳答案

简短的回答是分解一切。我把我的类(class)变成了一个哈希,然后是 Json,发送。从 Json 还原,并重新创建对象。

服务器端的CONTROLLER::

class UserRequestsController < ApplicationController
  # POST /user_requests
  # POST /user_requests.xml
  def add_request
    require 'rubygems'
    require 'json'
    #@user_request = UserRequest.new(params[:user_request])
    #@user_request = UserRequest.new(JSON.parse(params[:user_request]))
    #@user_request = UserRequest.new(params[:user_request].from_json)

    #puts @user_request

    #@custom = CustomRequest.new(params[:custom])
    #@custom = CustomRequest.new(JSON.parse(params[:custom]))
    #@custom = CustomRequest.new(params[:custom]).from_json
    #@custom = CustomRequest.new(params[:custom].from_json)

    @myHash = Hash.new()
    @myHash = params
    #puts (params[:url])

    #puts YAML::dump(params)
    # puts YAML::dump(params[:url])
    #@myHash = Hash.new(JSON.parse(params[:myHash]))
    #@myHash = Hash.new(params[:myHash]).from_json
    #@myHash = Hash.new(params[:myHash].from_json)

    puts "IT WORKS!"

    #puts @myHash
    #puts YAML::dump(@myHash)
    #@myHash.each { |k,v| puts "#{k} => #{v}" }\

    #@user_request = CustomRequest.new(@myHash[:url],@myHash[:depth])
    #@user_request = CustomRequest.new(@myHash[:url],@myHash[:depth])
    #@user_request = CustomRequest.new(Time.now,Time.now,params[:depth],params[:depth],nil)

    # Had to manually create the record because it couldnt take it from a single param
    @user_request = CustomRequest.create(:created_at =>Time.now,
    :updated_at => Time.now,
    :depth => @myHash[:depth],#myHash is the params broken into a hash
    :url => @myHash[:url],
    :status => "Yet to be crawled")

    puts  "YAML DUMP CUSTOM OBJECT"
    puts  YAML::dump(@user_request)

    respond_to do |format|
      if @user_request.save
        format.json { render :json => @myHash, :status => :created}
      else if @myHash.nil?
          format.json  { render :json => @user_request.errors, :status => :unprocessable_entity }
        #ß  format.xml  { render :xml => @user_request, :status => :created}#, :location => @user_request }
        else
          format.json  { render :json => @user_request.errors, :status => :unprocessable_entity }
        #ß  format.xml  { render :xml => @user_request, :status => :created}#, :location => @user_request }
        end
      end
    end

客户端模型post方法:

  def post_me

        res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add.json'),
                                  {'url' =>'UserRequest::url'}).as_json

关于ruby-on-rails - 在 Rails 中从 REST 获取 Post 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6696457/

相关文章:

ruby-on-rails - RoR 教程 Hartl 第 9.3 章

json - 从 Go 函数返回整个结构

json - Play Framework 2.2 : No Json deserializer found

ruby-on-rails - 页面未正确重定向 Ruby on Rails

ruby-on-rails - Heroku Postgres 上自动增量 ID 的差距

ruby-on-rails - Rails 回形针,DRY 配置

ruby-on-rails - 检查一个字符串中的单词是否在另一个字符串中的最快方法是什么?

ruby-on-rails - 在 rails 中用 <a href ="/phrase">phrase</a> 替换 {phrase}

Ruby 的对象#define_method 与模块#define_method

c# - 如何使用 Json.Net 将 JsonProperty 属性分配给 DLL 中类的属性?