如何将JSON写入Rails数据库

时间:2012-06-07 19:53:16

标签: ruby-on-rails-3 json post

我是rails的新手,现在试图了解它是如何工作的。我的目标是将一个JSON文件从浏览器(不同的域)发布到Rails应用程序,并将发送的数据保存到数据库中。

执行JQuery-Code后:

$(document).ready(function() {
  $("#testbutton").click(function() {
    var params = '{"comment": "Test", "creator": "Max", "name": "Testname", "url": "www.foo.com"}';
    $.ajax({
      type: "post",
      headers: { 'X-CSRF-Token': '<%= form_authenticity_token.to_s %>' },
      accepts: "application/json",
      contents: "application/json",
      data: params,
      url: 'http://localhost:3000/pages'
      });
    });
  });

我跳过在action-controller中验证authenticness-token:

skip_before_filter :verify_authenticity_token

现在,我不知道在create-action中要做什么,我必须更改它将解析JSON并将其写入数据库。我使用create-action的标准行为:

  def create
    @page = Page.new(params[:data])

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

服务器从网站接收数据,但无法解析它。

Started POST "/pages" for 127.0.0.1 at Thu Jun 07 21:48:53 +0200 2012
Processing by PagesController#create as undefined
  Parameters: {"{\"data\": {\"comment\": \"Test\", \"creator\": \"Fam Disselhoff\", \"name\": \"Renate\", \"url\": \"www.elesenroth.de\"}}"=>nil}
   (0.1ms)  begin transaction
  SQL (67.5ms)  INSERT INTO "pages" ("comment", "created_at", "creator", "name", "updated_at", "url") VALUES (?, ?, ?, ?, ?, ?)  [["comment", nil], ["created_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["creator", nil], ["name", nil], ["updated_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["url", nil]]

1 个答案:

答案 0 :(得分:2)

您可以使用以下解码方法进行处理。

parsed_json = ActiveSupport::JSON.decode(params[:data])
new_obj = Whatever.new
new_obj.field1 = parsed_json["field1"]
new_obj.field2 = parsed_json["field2"]
new_obj.save

希望这有帮助。