我在我的一个控制器中有一个create操作,它响应ajax和html请求。在create操作中,我使用find_or_initialize_by_such_and_such设置了一个实例变量(@location)。然后,我使用以下命令测试该位置是否已经存在:
if @location.id.nil?
@location.save
respond_with(@location, :location => root_path) do |format|
format.html { redirect_to root_path }
end
end这可以很好地工作,因为基本上部分(create.js.erb)将新保存的location对象追加到列表中。
当用户输入已经存在的位置(即具有id)时,就会出现问题。在这种情况下,我不希望将找到的位置附加到列表中,因为这会导致重复(所有位置都已经存在)。由于在该场景中@location.id.nil?为false,因此上述代码块中的代码显然不会执行,但我很难弄清楚如何处理这种情况。我试着这样做:
respond_with(nil, :location => root_path) do |format|
format.html { redirect_to root_path }
end 但是js.erb文件仍然获取@location实例变量,并执行将该对象添加到列表中的javascript。
因此,解决这个问题的最好方法是什么,以便在find_or_initialize_by返回已经创建的对象的情况下,响应不会执行javascript将该对象附加到列表中?
发布于 2011-03-29 00:09:25
删除
respond_with(nil, :location => root_path) do |format|
format.html { redirect_to root_path }
end 只留下这个
redirect_to root_path如果你没有任何额外的回应
https://stackoverflow.com/questions/5461756
复制相似问题