How do I create a web service with rails?
I have a silverlight application that needs to talk to a rails app to add a record. I have been able to get the silverlight app to successfully do the POST assuming everything g开发者_如何学Coes good. Now, however, I need to be able to make it more robust and have the rails app return error/success messages to the silverlight app in a format it can read (xml maybe?). I can modify the rails app and silverlight app as needed.
What is the best way to accomplish this with rails?
Rails handles most of this out-of-the-box.
You need to have a look at respond_to
This will return the records in @list as XML:
@list = Model.find(:all)
respond_to do |format|
format.html { render :action => "index" }
format.xml { render :xml => @list }
end
You can set status using http headers (for actions that don't return anything):
format.xml { head :ok }
And you can provide more complex messages, in this case returning Active Record errors and a status message:
format.xml { render :xml => @model.errors, :status => :unprocessable_entity }
This would be pretty much the same as any typical Rails app.
The only difference is that you'd be responding with xml (or json, or anything else Silverlight can parse) to any relevant actions. (Rather than rendering a page of HTML.)
精彩评论