嵌套控制器创建操作response_to无法渲染:新如果保存失败

时间:2014-06-23 09:33:46

标签: ruby-on-rails ruby ruby-on-rails-4 action actioncontroller

我有一个嵌套的Photo控制器,其操作如下:

  def create
    @photo = @gallery.photos.new(photo_params)
    if @photo.save
      flash[:notice] = "Created new photo"
    else
      flash[:error] = "Couldn't create photo"
    end
   respond_with [@gallery, @photo]
  end

如果照片参数有效,它会正确地重定向到gallery_photo_path,但是如果参数无效且@photo无法成功保存,而不是像我期望的那样渲染:new模板,它重定向到/galleries/1/photos,但不存在。

如果我不使用respond_with并对渲染进行硬编码,那么一切正常:

  def create
    @photo = @gallery.photos.new(photo_params)
    if @photo.save
      flash[:notice] = "Created new photo"
      redirect_to gallery_photo_path @gallery, @photo
    else
      flash[:error] = "Couldn't create photo"
      render :new
    end
  end

为什么respond_to无法在the docs中列出的保存文件时呈现新模板?

备注

我在控制器中使用respond_to :html,所有其他操作都按预期运行。

1 个答案:

答案 0 :(得分:2)

文档声明将respond_with与对象一起用作参数,而不是使用显式数组,因此

respond_with [@gallery, @photo]

应该是

respond_with(@gallery, @photo)
相关问题