ruby-on-rails-3
  • json
  • post
  • 2012-06-07 90 views 0 likes 
    0

    我是新來的rails,並試圖瞭解它如何在幾天內工作。我的目標是將瀏覽器(不同域)的JSON文件發佈到Rails應用程序,並將發送的數據保存到數據庫。如何將JSON寫入Rails數據庫

    繼jQuery的代碼被執行:

    $(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' 
         }); 
        }); 
        }); 
    

    我跳過驗證autheticity令牌在動作控制器:

    skip_before_filter :verify_authenticity_token 
    

    現在,我不知道是什麼在做創建行動我必須改變它將解析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]] 
    

    回答

    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 
    

    希望這會有所幫助。

    +0

    嘿約塞普,這已經是一個很好的幫助,謝謝!但是,它仍然沒有工作。我不得不使用'request.body.read'而不是'params [:data]',因爲數據不是形式編碼的。 – Randomtheories

    相關問題