Sunday, October 07, 2007

RESTful authentication with Rails 2.0

1. script/generate authenticated user --include-activation creates Rails 1.2.3 style migration.

So, I changed it to:

class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users, :force => true do |t|
t.string :login, :email, :remember_token
t.string :crypted_password, :limit => 40
t.string :salt, :limit => 40
t.string :activation_code, :limit => 40

t.datetime :remember_token_expires_at, :activated_at
t.timestamps
end
end

def self.down
drop_table "users"
end
end

2. The routes.rb looks like:

ActionController::Routing::Routes.draw do |map|
map.resources :users
map.resource :session

map.connect '', :controller => 'home', :action => 'index'

map.with_options :controller => "users" do |page|
page.signup "/signup", :action => "new"
page.activate "/activate/:activation_code", :action => "activate"
end

# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end

I had to define named route for signup because if I use new_user method in the application.rhtml, I kept getting error.

I don't know how to define the route in a RESTful way for activation. So I have named route for it.

3. In the form:

<% form_for @user do |f| -%>

<% end -%>

That's it. I am able to signup and activate using Rails 2.0. Of course I had to rename the .rhtml files to .html.erb. Now the Textmate shortcuts are broken, since it recogizes only rhtml files.

4 comments:

  1. You don't have to change the extension on your views.

    Rails 2.0PR (and from what I understand 2.0 in general) supports .rhtml views.

    ReplyDelete
  2. In section 1 you don't specify the name of the session controller, is this a typo, or deliberate?

    Also, in section 3 there doesn't seem to be any changes listed, is this deliberate too?

    I'm getting the following error - like a few other people:

    NameError in SessionController#new
    uninitialized constant SessionController

    The thing is my controller is pluralized, but it's looking for the singular by the looks of it. This thing has got me beat.

    ReplyDelete
  3. Thank you for writing this article. I've followed it twice now!

    ReplyDelete
  4. what creates Rails 1.2.3 style migration means? is it necessary?

    ReplyDelete