Ruby on Rails: reducing complexity of parameters in a RESTFul HTTP POST request (multi-model)
I'm using cURL to test a RESTFul HTTP web service. The problem is I'm normally submitting开发者_JAVA百科 a bunch of values normally like this:
curl -d "firstname=bob&lastname=smith&age=25&from=kansas&someothermodelattr=val" -H "Content-Type: application/x-www-form-urlencoded" http://mysite/people.xml -i
The problem with this is my controller will then have code like this:
unless params[:firstname].nil?
end
unless params[:lastname].nil?
end
// FINALLY
@person = People.new(params[:firstname], params[:lastname], params[:age], params[:from])
etc..
What's the best way to simplify this? My Person model has all the validations it needs. Is there a way (assuming the request has multi-model parameters) that I can just do:
@person = People.new(params[:person])
and then the initializer can take care of the rest?
Sorry, the question is a bit unclear. Are you asking how to nest the parameters in the request? That works like this:
curl -d "person[firstname]=bob&person[lastname]=smith&person[age]=25&person[from]=kansas&someothermodel[attr]=val" -H "Content-Type: application/x-www-form-urlencoded" http://mysite/people.xml -i
Then you can do
@person = People.new(params[:person])
精彩评论