Ruby on rails 在强参数中使用merge时,NilClass错误
我正在对我的应用程序进行测试 我有一个表单,它接受一个城市(由城市名称自动完成)和一些日期 因为我有一个自动完成功能,我必须通过查看城市的显示名称来获取城市idRuby on rails 在强参数中使用merge时,NilClass错误,ruby-on-rails,Ruby On Rails,我正在对我的应用程序进行测试 我有一个表单,它接受一个城市(由城市名称自动完成)和一些日期 因为我有一个自动完成功能,我必须通过查看城市的显示名称来获取城市id def trip_params params.require(:trip).permit(:start_date, :end_date).merge(:city_id => City.find_by_display(params[:trip][:city_id]).id) end 问题是如果用户在没有城市的情况下使用表单
def trip_params
params.require(:trip).permit(:start_date, :end_date).merge(:city_id => City.find_by_display(params[:trip][:city_id]).id)
end
问题是如果用户在没有城市的情况下使用表单。我得到一个错误:
undefined method `id' for nil:NilClass
因为没有找到任何记录。有什么更好的方法来构建它,以便在没有进入任何城市的情况下,我可以重定向回“新的”
创建方法以防有用
def create
@trip = current_user.trips.build(trip_params)
if @trip.save
flash[:success] = "Trip to #{@trip.city.name} added."
redirect_to root_path
else
flash.now[:error] = @trip.errors.full_messages
render 'new'
end
end
或
def create
if params[:trip][:city_id].blank?
flash[:error] = "some warning about the city"
render new
else
@trip = current_user.trips.build(trip_params)
if @trip.save
flash[:success] = "Trip to #{@trip.city.name} added."
redirect_to root_path
else
flash.now[:error] = @trip.errors.full_messages
render 'new'
end
end
end
def trip_params
if !params[:trip][:city_id].blank?
params.require(:trip).permit(:start_date, :end_date).merge(:city_id => City.find_by_display(params[:trip][:city_id]).id)
end
end