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?
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!
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|
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With