2010-10-21 71 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