Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a login form in the header for Devise and Rails

I want to put a login form in the header of my website. I use Rails 3.2.8 and the latest Devise. In the app/views/devise/sessions/new.html.erb file a login form is created with:

  <%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => 'main'}) do |f| %>
    <div><%= f.label :login %> <%= f.text_field :login, :placeholder => 'Enter username' %></div>
    <div><%= f.label :password %> <%= f.password_field :password, :placeholder => 'Enter password' %></div>
    <% if devise_mapping.rememberable? -%>
      <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
    <% end -%>
    <%= f.submit "Go" %>
  <% end %>

If I try to copy that code and put it in my application.html.erb, I get an error regarding that resource variable referenced above:

undefined local variable or method `resource' for #<#<Class:0x3cb62c8>:0x3c73b00>

So can I just use a normal rails form with /users/sign_in as the action? How do I tell devise where to redirect to after logging in?

like image 319
at. Avatar asked Dec 21 '22 14:12

at.


2 Answers

We have a wiki page for that on the Devise wiki:

https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app

Enjoy!

like image 173
José Valim Avatar answered Dec 23 '22 03:12

José Valim


You have to include @user = User.new in all the controller actions that will display the header with the login form.

For example, say you have a Pages controller with Home action. And you want to display the login form in the navigation of application layout.

class PagesController < ApplicationController
  def home
    @user = User.new
  end
end

On the application.html.haml, you'd have something like

- if user_signed_in?
  = link_to "sign out", destroy_user_session_path, method: :delete
- else
  = form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => 'main'}) do |f| 
  ...
like image 32
Jason Kim Avatar answered Dec 23 '22 04:12

Jason Kim