我有一个ChatController和一个@user变量.在主页面上,我显示@ user.name.我也有破坏和创建与ajax一起使用的方法,所以当我从聊天中删除一条消息时,@ user变为零.为了防止在nil对象上调用name的问
就像是:
class ChatController < ActionController::Base before_filter :find_user private def find_user @user ||= User.find_by_id(params[:user_id]) end end
您也可以考虑使用Inherited Resources为您自动执行此操作.