我正在修改 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
看法
当 start_masterlocation_id 存在时,我有 jQuery 向这个隐藏字段添加一个值。我还有 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