2013-12-13 33 views
1

我在Rails中體面,但在JavaScript和Ajax方面完全失敗。我該如何做一個Ajax update_attributes?

我想讓它使得當用戶點擊列表中的某個項目時,在該項目上使用Ajax調用update_attributes

這是我到目前爲止,但它是可怕的,我完全失去了。

在視圖:

<%= content_tag :div, class: "entry", data: {url: update_seen_count_url} do %> 
    <h5><a href="#"><%= simple_format user_notification.content %></h5> 
<% end %> 

update_seen_count(refered到在上述數據屬性)是指該控制器操作:

class UserNotificationsController < ApplicationController 
    def update_seen_count 
     ... (I think something like @usernotification.update_attributes but i have no idea) 
    end 
end 

任何想法?

回答

1

我假設你想要用戶點擊一個特定的鏈接。要使其工作,請使用link_to幫助程序並添加remote屬性。例如:

<%= link_to simple_format(user_notification.content), update_seen_count_url, remote: true %> 

然後,你可以通過調整你的控制器使用respond_to do |format|並添加action.js.erb文件通過JavaScript來改變用戶界面的響應。

+0

謝謝,我要試試這個。我如何向控制器傳遞被點擊的內容?意思是,我如何告訴它什麼update_attributes? – Philip7899

+0

只需將它作爲參數'update_seen_count_url(param)'添加到url即可。確保你的路線反映了這一點。 – beautifulcoder

+0

太好了,謝謝!這幾乎工作,但服務器日誌返回以下錯誤:'ActionView :: MissingTemplate(缺少模板user_notifications/update_seen_count,應用程序/ update_seen_count'。我認爲它是因爲控制器不在控制器中的任何地方重定向,但那是因爲我不't想要,你知道如何擺脫那個錯誤嗎? – Philip7899

0

首先定義一個路由,你的Ajax調用:

post "/my_controller/update_data" => "my_controller#update_data", :as => :update_data 
在你看來

然後執行Ajax調用:

$.ajax({ 
     type: "POST", 
     url: "<%= update_data_path %>", 
     dataType: "json", 
     data: { update_attr_name : update_attr_name, new_value : var} 
    }) 
    .done(function(resp){ 
     // when the controller responds 
     // you can "play" with the response for the controller 
     // for example if resp.my_status == "updated" 
    }) 
    .fail(function(){ 
     // when the response from the controller is not a JSON or a header error (4**, 5**) 
    }) 
    .always(function(){ 
     // run always 
}); 

最後你的控制器:

def update_data 
# you can retrieve here params[:update_attr_name] and params[:new_value] 
# then you can working on it, this should work: 
 # mod = Model.update_attributes(params[:update_attr_name].to_sym => params[:new_value]) 

# if ok 
    respond_to do |format| 
     format.json {render json: {:my_status => "updated", :data => "my_data"}} 
    end 
# if something goes wrong: fail the Ajax call 
rescue Exception => e 
    puts "Exception #{e.message}" 
    render :nothing => true, :status => 500 
end 

我個人更喜歡這種方式,因爲讓開發人員在這個過程中更具「動力」和靈活性。

+0

謝謝,我要試試這個。我如何向控制器傳遞被點擊的內容?意思是,我如何告訴它什麼update_attributes? – Philip7899

+0

@ Philip7899你可以在ajax調用中傳遞參數,我會更新我的答案 – damoiser