2010-10-21 74 views
0

我正在使用Rails應用程序,該應用程序在視圖方面每5分鐘向控制器發出一次Ajax調用,以檢查是否有爲特定用戶創建的任何新消息。現在我知道Rails(或MVC)的方式是使用Fat Models/Skinny控制器,我怎樣從我的控制器調用我的模型,以便數據在模型中返回?使用模型的導軌

這裏是我的控制器:

def get_all_notes_by_page 
    if request.xhr? 
     return Note.where("page_id = ?", params[:page_id]).count 
    end 
    end 

預先感謝所有幫助!

回答

0

我會成立(該代碼使用Prototype庫)定期監聽器:

new PeriodicalExecuter(function(pe) { 
    new Ajax.Request('/controllername/get_all_notes_by_page', { 
    onSuccess: function(response) { 
     // compare response value with some global variable 
    } 
    }); 
}, 300); 

,並在控制器端:

def get_all_notes_by_page 
    respond_to do |format| 
    format.js { render :text => Page.find(params[:page_id]).notes.count.to_s } 
    end 
end 

該控制器的方法是不夠骨感,但如果你真的想把它縮短,你可以在Page模型中定義一個count_notes方法。

1
if request.xhr? 
    Note.count_by_page_id(params[:page_id]) 
end