Fetching Post data from REST in Rails
This is a long question so i apologize if it takes a while to grasp. I'll keep it simple as possible.
I'm starting to get a little desperate here but I'm so close. I've been struggling with Ruby for a while and communicating with post and net::http. So what I've got at the moment is a hash being turned into json. sent across the wire using a post request from net::http and then I'm trying to turn it back into an object.
One route I explored was active record and active resource but after some issues with them on both sides decided to define my own model and then work out how to convert is and send it.
My Model
This model is called customRequest. Within it I have the post_me that takes 2 of the classes variables into a hash, turns it to json, then sends it.
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
So thats the custom request in a nutshell.
Questions
The bits I'm concerned about are:
- The receiving URL, I wrote add.json as the format is determined in the controller route. I don't know if that's necessary?
- Is it better to generate a hash from the variables and send that across for reconstruction or is it better to convert the whole class to_json and send it?
If I create the class as is in the rails console and send it, I get a nice 200 and a response in the terminal.
More Details
(NOTE: only read this bit if you really want to know whats going on in the scenes)
@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"]}
>>
Heres the same response If i dont convert it to Json:
{"myInteger":300,"myString":"testestest"}
=> #<Net::HTTPOK 200 OK readbody=true>
Please if someone could answer questions 1 and 2 I'd be greatful
Server Side
Heres the server side that needs to take the request and turn it back into Json and an object. Ive tried a bunch of different things which most have been commented out.
Basically I'll either get a 200 response with the details in the tag but when I try to puts the hash object, I get nothing/
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)
Heres the multiple attempt of breaking it apart and turning it back into an object.
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)
@myH开发者_开发知识库ash = 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
They're all pretty much the same except one was me trying to recreate the object from the sent hash and another was me trying to recreate hash_to_json to hash_from_json
More Questions
So:
- Am I creating the object correctly with the params(:myHash) or should i be referencing each variable individually?
- are the params automatically turned back into readable format or do i need to put to from or parse JSON. In regards to that, does it matter which one I use?
- Am i reconstructing the object correctly, why is putting my has displaying nothing?
- (optional) are there any easy ways to store it in a table thereafter?
Short answer is break everything down. I turned my class to a hash, then to Json, send. Revert from Json, and recreate the object.
CONTROLLER on server side::
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
Model post method on client side:
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
精彩评论