I am working on a rails app that on the view side makes an Ajax call every 5 minutes or so to a controller to check if there are any new messages that were created for a particular user. Now I know the way of Rails (or MVC for that matter) is to use Fat Models/Skinny Controllers, how would I call my model from my controlle开发者_开发问答r so that the data is being returned in the model?
Here is my controller:
def get_all_notes_by_page
if request.xhr?
return Note.where("page_id = ?", params[:page_id]).count
end
end
Thanks in advance for all of the help!
if request.xhr?
Note.count_by_page_id(params[:page_id])
end
I'd set up periodical listener (this code is using Prototype library):
new PeriodicalExecuter(function(pe) {
new Ajax.Request('/controllername/get_all_notes_by_page', {
onSuccess: function(response) {
// compare response value with some global variable
}
});
}, 300);
and on the controller side:
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
This controller method is skinny enough, but if you really want to make it shorter, you can define a count_notes
method in the Page model.
精彩评论