0
0
Ruby on Railsframework~10 mins

Before and after filters in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a before filter in a Rails controller.

Ruby on Rails
class PostsController < ApplicationController
  [1] :authenticate_user

  def index
    # list posts
  end
end
Drag options to blanks, or click blank then click option'
Abefore_action
Bafter_action
Caround_action
Dskip_action
Attempts:
3 left
💡 Hint
Common Mistakes
Using after_action instead of before_action
Using skip_action which disables filters
Using around_action which wraps actions
2fill in blank
medium

Complete the code to define an after filter that runs only on the show action.

Ruby on Rails
class UsersController < ApplicationController
  after_action :log_view, only: [1]

  def show
    # show user
  end
end
Drag options to blanks, or click blank then click option'
A[:index]
B[:edit]
C[:show]
D[:destroy]
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong action name in the only option
Forgetting to wrap the action name in an array
Using except instead of only
3fill in blank
hard

Fix the error in the filter definition to run a method after every action.

Ruby on Rails
class CommentsController < ApplicationController
  [1] :clear_cache

  def create
    # create comment
  end
end
Drag options to blanks, or click blank then click option'
Aafter_filter
Bafter_action
Cbefore_filter
Dbefore_action
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated filter methods like before_filter or after_filter
Using before_action instead of after_action
4fill in blank
hard

Fill both blanks to run a method before all actions except edit and update.

Ruby on Rails
class ProfilesController < ApplicationController
  [1] :check_permissions, except: [2]

  def edit
    # edit profile
  end

  def update
    # update profile
  end
end
Drag options to blanks, or click blank then click option'
Abefore_action
Bafter_action
C[:edit, :update]
D[:show, :index]
Attempts:
3 left
💡 Hint
Common Mistakes
Using after_action instead of before_action
Using except with wrong action names
Not wrapping actions in an array
5fill in blank
hard

Fill all three blanks to define a before filter that runs only on create and update, and an after filter that runs on destroy.

Ruby on Rails
class ArticlesController < ApplicationController
  [1] :verify_user, only: [2]
  [3] :log_deletion, only: [:destroy]

  def create
    # create article
  end

  def update
    # update article
  end

  def destroy
    # destroy article
  end
end
Drag options to blanks, or click blank then click option'
Abefore_action
B[:create, :update]
Cafter_action
Dbefore_filter
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated before_filter
Mixing up before and after actions
Not specifying the correct actions in only