Skip to content

Instantly share code, notes, and snippets.

@hmans hmans/info.md
Last active Sep 25, 2017

Embed
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
  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
You can’t perform that action at this time.