我正在改造一个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,它在不存在字段属性时删除它。
<%= hidden_field :newsavedmap, :start_masterlocation_id, :id => "start-masterlocation-id-field" %>
最后,这里是控制器中抛出错误的部分。这是包含表单的页面的控制器(Maptry),而不是Newsavedmap的控制器。我认为我必须删除@newsavedmap.id、@newsavedmap.mapname和@newsavedmap.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
发布于 2013-09-21 07:18:25
我通过忽略零问题解决了这个问题。相反,我用
!@newsavedmap.start_masterlocation_id.blank?
这将评估记录中的数据是否为空,然后执行还是不执行。显然,这会导致不想要的“空白”数据留在我的数据库中,所以这并不理想,但它帮助我推进了这个项目。如果能直接处理零问题,并告诉我如何让Rails在表单中忽略空白数据,我将不胜感激。
https://stackoverflow.com/questions/18603320
复制相似问题