Please help me to login with username or email using Rails 3.I have two model i.e-Admin and User.Admin can only login through email id and user can only login through username.I need both login process.Please check my below codes and help me to resolve this issue.
views/admins/index.html.erb
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<%= form_for :admin,:url => {:action => "login" ,:controller => "sessions" } do |f| %>
<%= f.text_field :login,placeholder:"Enter your email or username" %>
<%= f.password_field :password,placeholder:"Enter your password" %>
<%= f.submit "Log in" %>
<% end %>
<% if @admin.try(:errors).try(:any?) %>
<div id="error_explanation">
<h2><%= pluralize(@admin.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @admin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
</div>
sessions/sessions_contrtoller.rb
class SessionsController < ApplicationController
def login
@admin=Admin.authenticate(params[:admin][:email], params[:admin][:password])
if @admin
session[:user_id]=@admin.id
cookies.signed[:user_id]=@admin.id
flash[:notice]="Login Successfull"
flash[:color]="valid"
redirect_to :action => 'index', :controller => "homes"
else
flash[:notice]="Login failed"
flash[:color]="invalid"
render 'admins/index'
end
end
def removeadmin
session[:user_id] = nil
cookies.delete :user_id
flash[:notice]="user logged out successfully"
flash[:color]="valid"
redirect_to :action => 'index', :controller => 'admins'
end
end
model/admin.rb
class Admin < ActiveRecord::Base
attr_accessible :email, :name, :password, :phoneno
attr_accessor :login
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates_length_of :password, :in => 6..20, :on => :create
has_many :user
def self.authenticate(email, password)
admin = find_by_email(email)
if admin && admin.password==password
admin
else
nil
end
end
end
model/user.rb
class User < ActiveRecord::Base
belongs_to :admin
attr_accessible :email, :password_hash, :password_salt, :phoneno, :user_name,:password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
As i am new to RoR. Please help me to resolve this issue.
Aucun commentaire:
Enregistrer un commentaire