admins_create_and_edit

Written . Tagged Ruby, Ruby on Rails.

With RESTful Rails resource controllers, it’s a fairly common pattern that creating and editing a resource is for admins only, but showing, indexing etc is for everyone.

Assuming an admin_only before filter, add this protected method to your ApplicationController:

1
2
3
4
5
  def self.admins_create_and_edit(options={})
    actions = [:new, :create, :edit, :update]
    actions += Array(options[:and])
    before_filter :admin_only, :only => actions
  end

Now, you can just do

1
admins_create_and_edit

in your controller to protect the four actions around creation and editing. You can optionally pass additional methods to protect, like

1
admins_create_and_edit :and => :destroy

or

1
admins_create_and_edit :and => [:destroy, :invert]