2016-05-12 74 views
0

嘿,大家我有一個問題來設置我的應用程序。它使用shopify API,基本上它是通過視圖獲取一些數據並將其發送到控制器,但我有問題將其傳遞給控制器​​中的另一個方法以使用API​​來保存數據。Rails Ajax調用:將JSON傳遞給單獨的控制器方法

這裏是我的代碼:

控制器

class BuilderController < ShopifyApp::AuthenticatedController 
    def index 
    urlval = request.fullpath 
    @urlCheck = urlval.split('/').last 
    end 
    def show 
    url = request.fullpath 
    @urlID = url.split('/').last 
    @customers = ShopifyAPI::Customer.search(query: "id:"+ @urlID) 
    #need to get a way to retrieve the ajax call info here to pass into the update 
    end 
    def updateCustomer(notes) 
     @customers.each do |cus| 
     cus.note = notes 
     cus.save() 
     end 
    end 
    def new 
    notes = params[:notes] 
    updateCustomer(notes) 
    render json: notes 
    end 
end 

查看

<button id="test">TEST</button> 

<script> 
var butt = document.getElementById('test'); 
butt.addEventListener("click",function(){ 
    $.ajax({ 
    url: "/builder/new", 
    type: "GET", 
    data: { 
      "notes": [ 
       "test", 
       "test2" 
      ] 
     }, 
    success: function(data,text,xhr) { 
     console.log(text); 
     console.log(xhr); 
     console.log(data); 
     alert('successfully'); 
    }, 
    error: function(data,error){ 
     console.log(data); 
     console.log(error); 
     alert("help"); 
    } 
    }); 
}); 
</script> 

回答

0

不是一個完全獨立的方法相反,你進去看了 的respond_to方法? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to

你可以這樣做(假設HTML是主要的請求類型,如果變化是不是):

def index 
    respond_to do |format| 
    format.html { actions } 
    format.json { actions } 
    end 
end 

此我們使用相同的動作中適應不同的請求類型的方法。如果我誤解了你的問題,請告訴我。

+0

的動作是我updatecustomer方法實現? – dpat

0

如果 它們匹配,也可以 提供一組提供條件,限制和爲了您可以使用此

update_all(更新)公共 更新與提供的細節全部記錄。此方法構造一條SQL UPDATE語句,並將其直接發送到數據庫。它沒有實例化涉及模型的 ,它不會觸發Active Record回調或 驗證。 http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all

def new 
notes = params[:notes] 
@customer.update_all({note: notes}) 

respond_to do |format| 
    format.html {} 
    format.json { json: @customer.json } 
end 
end 
+0

我爲什麼需要一個SQL類型語句時我有點困惑,因爲我根本不使用數據庫?也許我只是誤解 – dpat

相關問題