ruby-on-rails – 如何将数据从Matlab发送到Rails

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何将数据从Matlab发送到Rails前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Rails和Web开发的新手.

我在Matlab中生成了一堆对象,我想将这些对象发送到我的Rails应用程序中的数据库.谁能告诉我如何做到这一点?

到目前为止,在Rails端,我已经为我的数据生成了基本的脚手架.我可以使用’/ myobjects / new’中的表单将对象添加到我的数据库中.

在Matlab端,我一直在尝试使用HTTP POST请求添加对象,如下所示:

s = urlread('http://localhost:3000/myobjects.json','POST',{'myobject','{name1:''value1''}'})

这会失败并将以下内容打印到Rails控制台:

Started POST "/myobjects.json" for 127.0.0.1 at 2012-06-16 11:48:28 -0400
Processing by MyobjectsController#create as JSON
  Parameters: {"myobject"=>"{name1:'value1'}"}
WARNING: Can't verify CSRF token authenticity
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `stringify_keys' for "{name1:'value1'}":String):
  app/controllers/myobjects_controller.rb:43:in `new'
  app/controllers/myobjects_controller.rb:43:in `create'

这种方法可能会偏离基础,但希望上面的代码能够明确我的目标.谁能告诉我如何修复我的代码,或者建议一个更好的策略来将我的数据导入rails?

编辑

目前我的new和create方法看起来像这样(但我可以根据需要更改它们)

# GET /irs/new
  # GET /irs/new.json
  def new
    @ir = Ir.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @ir }
    end
  end

  # POST /irs
  # POST /irs.json
  def create
    @ir = Ir.new(params[:ir])

    respond_to do |format|
      if @ir.save
       format.html { redirect_to @ir,notice: 'Ir was successfully created.' }
       format.json { render json: @ir,status: :created,location: @ir }
      else
        format.html { render action: "new" }
        format.json { render json: @ir.errors,status: :unprocessable_entity }
      end
    end
  end

解决方法

最后,我放弃了尝试用matlab的内置函数做到这一点.相反,我导入了一个Java库( Apache HttpComponents).这是我提出的脚本.这样做了.
javaaddpath(['utils/httpcomponents-client-4.2/lib/httpcore-4.2.jar']);
javaaddpath(['utils/httpcomponents-client-4.2/lib/httpclient-4.2.jar']);


import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity


httpclient = DefaultHttpClient();

httppost = HttpPost('http://127.0.0.1:3000/myobjects.json');
httppost.addHeader('Content-Type','application/json');
httppost.addHeader('Accept','application/json');

params = StringEntity('{"field1":"value1"}');
httppost.setEntity(params);

response = httpclient.execute(httppost);
原文链接:/ruby/274205.html

猜你在找的Ruby相关文章