开发者

Creating a new rails database record from an external script?

I'm trying to send a POST request from an external Ruby script to a Rails app via HTTP#post_form. The request is made to the create action (i.e. the URI is http://server/controller).

If I encode a single parameter into the request, everything is fine:

HTTP::post_form(uri, { :my_param => "value" })

Though I do have to explicitly pull out my_param from params manually, in the controller. This seems inefficient, and breaks creating a new record from within the app itself (because that parameter is not there). I'm consequently trying to make my script pose as Rails itself, passing the appropriate data as the controller would expect it, e.g.

HTTP::post_form(uri, { :object => { :my_param => "value" } })

However, this doesn't work. post_form seems to be escaping my hash into something different, i.e.

{ "object" => [\"my_param\", \"value\"] }

Which obviously doesn't do the same thing. Am I missing something obvious in the way I'm passing the d开发者_如何学Goata? Or can I not achieve what I'm after (creating a new record from outside the app)?


One straightforward way might be to simply imitate how Rails formats its parameters, like this:

params = { :my_param => "value", ... }
params = Hash[params.map { |key,value| ["object[#{key}]",value] } ]

HTTP::post_form(uri, params)

Edit: Well, look at that, I looked around a bit and found that Rails actually gives you a method to do the same thing using their own mechanism:

require 'active_support/core_ext'
...
HTTP::post(uri, parameters.to_param)

The to_param method will treat Arrays correctly, and everything else too. Notice that in this case you want to use HTTP::post, not post_form, since the parameters are already converted to a string.


I don't know much about post_form but the natural solution for me would be to use an ActiveResource object.

ActiveResource is available to ruby as well as to Rails. you use it just like you use a model only it posts and gets using XML There is a Railscast on how this works here

http://railscasts.com/episodes/94-activeresource-basics

http://railscasts.com/episodes/95-more-on-activeresource

I think you'll find that this is a better fit for your requirements than post_form but as I say, I'm not familiar with post_form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜