0

我是 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'
      });
    });
  });

我跳过验证动作控制器中的真实性令牌:

skip_before_filter :verify_authenticity_token

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

  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]]
4

1 回答 1

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

希望这可以帮助。

于 2012-06-07T21:13:09.903 回答