为什么Rails在我的表单中没有识别为空?

我正在改造一个Rails 2网站。 现在,我收到一个错误,我认为这是因为一个值被提交为空白而不是.nil。 但是,我试图保持零状态似乎不起作用。 我感谢您提供的任何帮助。

从模型,基于Make blank params [] nil

NULL_ATTRS = %w( start_masterlocation_id ) before_save :nil_if_blank protected def nil_if_blank NULL_ATTRS.each { |attr| self[attr] = nil if self[attr].blank? } end 

视图

我有jQuery在start_masterlocation_id存在时为这个隐藏字段添加一个值。 我还有jQuery在不存在时删除了field属性。

   "start-masterlocation-id-field" %> 

最后,这是控制器抛出错误的部分。 这是保存表单(Maptry)的页面的控制器,而不是Newsavedmap的控制器。 我想我必须删除@ newsavedmap.id,@ newsavedmap.mapname和@newavedavedmap.optimize行,因为我要使用表单处理程序,但我不认为这与此错误有关。

调节器

  def maptry @itinerary = Itinerary.find(params[:id]) if @itinerary.user_id == current_user.id respond_to do |format| @masterlocation = Masterlocation.find(:all) format.html do end format.xml { render :xml => @masterlocation } format.js do @masterlocation = Masterlocation.find(:all) render :json => @masterlocation.to_json(:only => [:id, :nickname, :latitude, :longitude]) end end if params[:newsavedmap_id] @newsavedmap = Newsavedmap.find(:first, :conditions => {:id => params[:newsavedmap_id]}) @waypoint = Waypoint.find(:all, :conditions => {:newsavedmap_id => params[:newsavedmap_id]}) @newsavedmap.id = params[:newsavedmap_id] @newsavedmap.mapname = Newsavedmap.find(:first, :conditions => {:id => params[:newsavedmap_id]}).mapname @newsavedmap.optimize = Newsavedmap.find(:first, :conditions => {:id => params[:newsavedmap_id]}).optimize if !@newsavedmap.start_masterlocation_id.nil? @start_name = Masterlocation.find(:first, :conditions => {:id => @newsavedmap.start_masterlocation_id}).name end if !@newsavedmap.end_masterlocation_id.nil? @end_name = Masterlocation.find(:first, :conditions => {:id => @newsavedmap.end_masterlocation_id}).name end else @newsavedmap = Newsavedmap.new end else redirect_to '/' end end 

错误当数据库中存在start_masterlocation_id时,不会发生此错误

  undefined method `name' for nil:NilClass 

我通过忽略零问题解决了这个问题。 相反,我用过

  !@newsavedmap.start_masterlocation_id.blank? 

这将评估记录中的数据是否为空,然后执行或不执行某些操作。 显然,这会导致不需要的“空白”数据留在我的数据库中,因此它并不理想,但它帮助我推进了项目。 我很感激任何直接处理nil问题的回复,并告诉我如何让Rails忽略表单中的空白数据。