This gem gives you a restful controller with one line of code. It's like invisible scaffolding.
The following controller is equalent to the controller generated by Rails 4 scaffolding:
class PostsController < ActionController::Base
restful_controller
private
def post_params
params.require(:post).permit(:title, :body)
end
end
By default restful-controller
will provide you with all 7 default actions. If you need only a few actions, you can do the following:
class PostsController < ActionController::Base
restful_controller :index, :show
end
To get all standard actions except only
and show
:
class PostsController < ActionController::Base
restful_controller except: [:index, :show]
end
If you need an action with custom code, you can simply rewrite it, restful-controller
won't get into your way.
class PostsController < ActionController::Base
restful_controller
def show
# Here you already have access to @post, as the gem follows Rails 4 convention
# of setting it inside a private set_post method.
end
end
If you need a custom way to retrieve records, you can rewrite the set_#{model_name}
method (for PostsController it is set_post
):
class PostsController < ActionController::Base
restful_controller
private
def set_post
@post = current_user.posts.find(params[:id])
end
end
Add this line to your application's Gemfile:
gem 'restful-controller'
And then execute:
$ bundle
Or install it yourself as:
$ gem install restful-controller
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request