4

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?

at.
  • 45,606
  • 92
  • 271
  • 433

2 Answers2

10

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!

José Valim
  • 47,390
  • 9
  • 122
  • 109
  • Perfect. How do I direct a user to a particular page afterwards? – at. Oct 26 '12 at 21:09
  • I believe there is a wiki entry for that too. But in few words, you just need to override `after_sign_in_path_for(resource)` in your ApplicationController. – José Valim Nov 02 '12 at 13:03
  • yes, but then I wasn't able to easily see how to do the default action if I didn't specify the target page. For example, normally I click on a link that has the `before_filter :authenticate_user!` call in the controller, so it takes me to the login page first. I want a login to then take me to that originally requested page. – at. Nov 03 '12 at 03:56
  • There is a page in the wiki for that too: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update – José Valim Jan 02 '13 at 07:44
1

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| 
  ...
Jason Kim
  • 15,110
  • 12
  • 60
  • 97