Skip to content

Instantly share code, notes, and snippets.

@hmans
Last active September 25, 2017 01:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmans/6dd1012952eea9b7bc459669da4c9d42 to your computer and use it in GitHub Desktop.
Save hmans/6dd1012952eea9b7bc459669da4c9d42 to your computer and use it in GitHub Desktop.
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
  load_and_authorize_resource

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

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

  private

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

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