Question

this newbie here is smacking his head with webservices over Rails. Perhaps someone could ease my pain?

I've created a simple rails app, and generated the scaffold MyRecords. Then I'm trying to create a record over irb with the code below :

testWS.rb

require 'HTTParty'

class MyRecordCreate
  include HTTParty
  base_uri 'localhost:3000'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  def post(text)
    options = { :body => { name:text} }
    self.class.post('/my_records', options)
  end
end


response = HTTParty.get("http://localhost:3000/my_records/new.json")
print response

record = MyRecordCreate.new("","").post("test remote record")
print record

With the code above, I managed to create a record. the thing is that my Record (which only has the column "name") is created with an empty name!

Any suggestions on this one?

I'm longing to slice this despair piece by piece.

Thank you for your contribute.

Was it helpful?

Solution

Try adding these two lines to your HTTParty class:

format :json
headers "Accept" => "application/json"

These tell httparty and the remote service to which it connects to send and receive JSON. For your example (with .json at the end of the URL) it isn't necessary to add the second line, but I find it is good practice and keep it anyway.

The next problem is that Rails expects your uploaded data to be inside the top level name of your object. So, for your example, the options line should look something like:

options = { :body => { :person => { :name => text } } }

Replace person with the name of the model that you are attempting to create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top