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
andor
as control flow operators increate
andupdate
. Don't you judge me!