Rails: Trying to better understand respond_with syntax

354 views Asked by At

I am refactoring some older code and am trying to get a better grasp on the respond_with syntax...

Here is my controller:

class VideosController < ApplicationController
  authorize_resource
  before_filter :authenticate_user!

  respond_to :json, :js, :html

  def index
    @video = Video.new(athlete_id: current_user.id, sport_id: current_athlete_sport.id)
    @videos = current_user.videos_for_sport(current_athlete_sport).order("date DESC")
    respond_with @videos
  end

  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: edit_videos_path
  end

  def update
    @video = Video.find(params[:id])
    @athlete = Athlete.find(@video.athlete_id)
    update_featured = params[:video][:featured].eql?("1") && !current_user.featured_video.blank? && current_user.featured_video.id != @video.id
    current_user.featured_video.update_attribute(:featured, false) if update_featured

    if @video.update_attributes(params[:video])
      flash[:notice] = "Successfully Updated!"
      log_activity(@video.logging_information)
    else
      flash[:notice] = @video.errors.full_messages.to_sentence
    end

    respond_with @video, location: edit_videos_path do |format|
      format.json { render json: { message: flash[:notice], reload: update_featured }  }
    end
  end

  def show
    @video = Video.find(params[:id])
    render layout: false
  end

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

    if @video.destroy
      flash[:notice] = 'Video was successfully destroyed'
      log_activity(@video.logging_information)
    else
      flash[:notice] = 'There was a problem destroying that video'
    end

    respond_with @athlete, location: edit_videos_path
  end

  def rotate
    @video = Video.find(params[:id])
    @encoding = @video.encode(params[:direction])

    if @video.update_attributes(thumbnail_url: @encoding.screenshots.first, mp4_video_url: @encoding.url)
      flash[:notice] = "Your video was successfully rotated"
    else
      flash[:notice] = "There was a problem rotating that video"
    end

    respond_with @video, location: edit_videos_path
  end

end

Just curious to know if I doing things the right way, more so in the update/create methods

1

There are 1 answers

0
Nick Veys On BEST ANSWER

It's really just a convenience when your controller can respond to a variety of format requests.

This is a pretty good article describing it.