0

我正在重构一些旧代码,并试图更好地掌握respond_with语法......

这是我的控制器:

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

只是想知道我是否以正确的方式做事,在更新/创建方法中更是如此

4

1 回答 1

1

当您的控制器可以响应各种格式请求时,这实际上只是一种方便。

这是一篇很好的文章来描述它。

于 2013-08-22T19:38:16.610 回答