Skip to content

Quickstart cantango with devise

kristianmandrup edited this page Oct 18, 2011 · 8 revisions

This Quickstart guide builds on the basic Quickstart. We simply adjust it to work with Devise.

Install devise

In your Gemfile

gem 'devise'

$ bundle
$ rails g devise:install

Create first Devise user

Note: CanTango can be used with any ORM (data store)

$ rails g devise user
$ rake db:migrate

This creates a User model setup with some devise strategies you can adjust as you see fit. If you followed the basic Quickstart now is the time to remove current_user from ApplicationController and let Devise take over!

Create model to authorize

Lets scaffold a new Post model

$ rails g scaffold Post title:string description:text
$ rake db:migrate

Check that you can navigate around and create Posts as a guest.

Configure authorization logic

Now let's require authentication of users trying to access posts, except for the index page.

class PostsController < ApplicationController
  before_filter :authenticate_user!, :except => [:index]
end

We also edit views/posts/index.html.haml to put some protections in place in the views

= link_to('New post', new_post_path) if user_can?(:create, Post)
- posts.each do |post|
  %tr
    %td
      = link_to(post.title, post_path(post)) if user_can?(:read, post)
    %td
      = link_to("Edit", edit_post_path(post)) if user_can?(:edit, post)
    %td
      = link_to("Delete", delete_post_path(post)) if user_can?(:delete, post)

This should limit your actions as a guest visitor. If you login you will have more actions available, depending on your permissions!

CanTango comes with a CanTango::Rails::Helpers::RestHelper module, which is now automatically made available to views and controllers. This allows you the following shorthand in place of the above example:

= link_to_new(Post, :user)
- posts.each do |post|
  %tr
    %td
      = link_to_view(post, :user)
    %td
      = link_to_edit(post, :user)
    %td
      = link_to_delete(post, :user)