Skip to content

Instantly share code, notes, and snippets.



Last active Sep 25, 2017
What would you like to do?
RESTful Rails Controller, 2017 Edition

This is a RESTful Rails controller, implementing all 7 RESTful actions. In my Rails apps, 9 out of 10 controllers will end up looking like this.

class PostsController < ApplicationController

  def create and redirect_to(@post) or render(:new)

  def update
    @post.update(post_params) and redirect_to(@post) or render(:edit)


  def post_params
    params.require(:post).permit(:title, :html)

Some notes:

  • The heavy lifting is done by CanCanCan's load_and_authorize_resource. It will load the correct resources for the requested action (and according do your authorization rules) and save you from writing all that @posts = Post.all boilerplate. It's really good, check it out!
  • Fun Rails fact: if your controller action doesn't actually do anything (on top of existing filters etc.), you don't even need to implement it at all. This is why there are no show, index etc. methods in here; they would just be empty. (You still need the views, though!)
  • I'm having a little fun with and and or as control flow operators in create and update. Don't you judge me!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment