Skip to content

How To: Display a custom sign_in form anywhere in your app

Matias Korhonen edited this page Jan 14, 2014 · 11 revisions

It’s easy to create a custom login form that can be used anywhere in your application.

Here’s an example in HAML:

= form_tag session_path(:user) do
  = text_field_tag 'user[email]'
  = password_field_tag 'user[password]'
  = check_box_tag 'user[remember_me]'
  = label_tag 'user[remember_me]', 'Remember me'
  %button Sign in
  = link_to "Forgot your password?", new_password_path(:user)

Another example with form_for and posting to user_session_path:

<%= form_for(:user, :url => session_path(:user)) do |f| %>
  <%= f.text_field :email %>
  <%= f.password_field :password %>
  <%= f.check_box :remember_me %>
  <%= f.label :remember_me %>
  <%= f.submit 'Sign in' %>
  <%= link_to "Forgot your password?", new_password_path(:user) %>
<% end %>

Note: “user” in this context is the resource you specified when setting up Devise.

Warning for client_side_validations
Whilst the above method works, it should be noted that using the name of a resource as the first parameter for form_for is now deprecated in Rails. I ran into this problem whilst trying to integrate client_side_validations with devise and it choked on this form. I don’t know if this is the best work around but in the end, I got it working by leaving the devise form_for as it looks normally:
form_for(resource, :as => resource_name ... )

Now the trick is defining those helper methods in other controllers. Assuming your devise model is called “user”, place the following methods either in the helper class of the controller you are using to display the form or in your application helper:

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

Another advantage of this method is that you don’t need to alter the default devise forms. Just move them into a partial and render them wherever you want.

Source: http://pupeno.com/blog/show-a-devise-log-in-form-in-another-page/

Clone this wiki locally