Month: August 2010

  • Update: there’s a new version of this post covering Devise 4.0.0: Show a devise log in or sign up forms in another page

    Devise create various forms, among them one for signing up and one for logging in of course. These are the forms as they are generated in Devise 1.0.8:

    <h2>Sign up</h2>
    
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= f.error_messages %>
    
      <div>
        <%= f.label :email %><br>
        <%= f.text_field :email %>
      </div>
    
      <div>
        <%= f.label :password %><br>
        <%= f.password_field :password %>
      </div>
    
      <div>
        <%= f.label :password_confirmation %><br>
        <%= f.password_field :password_confirmation %>
      </div>
    
      <div>
        <%= f.submit "Sign up" %>
      </div>
    <% end %>
    
    <%= render partial: "shared/devise_links" %>

    and

    <h2>Sign in</h2>
    
    <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
      <div>
        <%= f.label :email %><br>
        <%= f.text_field :email %>
      </div>
    
      <div>
        <%= f.label :password %><br>
        <%= f.password_field :password %>
      </div>
    
      <% if devise_mapping.rememberable? %>
        <div>
          <%= f.check_box :remember_me %>
          <%= f.label :remember_me %>
        </div>
      <% end %>
    
      <div>
        <%= f.submit "Sign in" %>
      </div>
    <% end %>
    
    <%= render partial: "shared/devise_links" %>

    If you try to put them somewhere else you’ll run into some problem. There are some variables/methods those forms use that you’ll be lacking, specifically: resource_name, resource and for logging in also devise_mapping. I’ve recently tried to put them both in the homepage for an upcoming project of mine and this is how I’ve solved it:

    module ContentHelper
      def resource_name
        :user
      end
    
      def resource
        @resource ||= User.new
      end
    
      def devise_mapping
        @devise_mapping ||= Devise.mappings[:user]
      end
    end