Rails: respond_with not working properly during create action

320 views Asked by At

Here is my create method in my controller (old way):

  def create
    @athlete = Athlete.find(params[:video][:athlete_id])
    @video = Video.new(params[:video])

    if @athlete.can_add_another_video? && @video.save
      flash[:notice] = "Successfully created"
      PandaWorker.perform_async(@video.id)
      log_activity(@video.logging_information)
    else
      flash[:notice] = @video.errors.full_messages.to_sentence
    end

    respond_with @video, location: athlete_profile_showcase_path
  end

New way:

  def create
    @athlete = Athlete.find(params[:video][:athlete_id])
    @video = Video.new(params[:video])

    if @athlete.can_add_another_video? && @video.save
      flash[:notice] = "Successfully created"
      PandaWorker.perform_async(@video.id)
      log_activity(@video.logging_information)
      respond_with @video, location: athlete_profile_showcase_path
    else
      flash[:notice] = @video.errors.full_messages.to_sentence
      redirect_to athlete_profile_showcase_path
    end
  end

The first piece of code above fails if the saving of the video object doesn't happen. It attempts to redirect to the VideosController#new method instead of following the location I specified. Obviously the first way is wrong, but I am not sure why. Any help would be greatly appreciated! Still trying to fully understand the respond_with syntax

1

There are 1 answers

0
Vadym Chumel On

Specified 'location' only used when your model is valid. Have a look at responder docs Custom Options is what you need. Also check answer here - defining custom responder can be much more cleaner.