undefined method `downcase' for nil:NilClass railstutorial - ruby-on-rails

I try railstutorial rails4.0
now 9.2.0 and no Rspec error.
but rails s has NoMethodError in Users#index when open /users
why?
app / models / user.rb
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
app / controllers / users_controller.rb
class UsersController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update]
before_action :correct_user, only: [:edit, :update]
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def edit
end
def update
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
#Before actions
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
end
app / views / users / index.html.slim
- provide(:title, 'All users')
h1 All users
ul.users
- #users.each do |user|
li
= gravatar_for user, size: 52
= link_to user.name, user
app / helpers / users_helper.rb
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end

I have not tried. but it can be something like this.
before_save { self.email = email.downcase if email}

Your error would seem to be coming from the first line of the gravatar_for method, which calls user.email.downcase, suggesting you have at least one user with a nil email address in the database.

Related

Why is current_user called on render in controller?

I'm getting the following error when trying access the log in method of my sessions controller:
JWT::DecodeError (Nil JSON web token):
lib/json_web_token.rb:11:in `decode'
app/helpers/sessions_helper.rb:15:in `current_user'
app/controllers/api/sessions_controller.rb:11:in `create'
If I comment out my render json: user in my controller response, all is good, except I need to respond with the user...Why on earth is the current_user method called on through line 11 of the sessions_controller.rb. Here's the relevant code:
lib/json_web_token.rb
require 'jwt'
class JsonWebToken
def self.encode(payload, expiration = 24.hours.from_now)
payload = payload.dup
payload['exp'] = expiration.to_i
JWT.encode(payload, Rails.application.secrets.json_web_token_secret)
end
def self.decode(token)
JWT.decode(token, Rails.application.secrets.json_web_token_secret).first
end
end
sessions_helper.rb
require 'json_web_token'
module SessionsHelper
def create_session(user)
session[:user_id] = user.id
end
def current_user
auth_token = request.headers["Authorization"]
if auth_token
auth_token = auth_token.split(" ").last
begin
decoded_token = JsonWebToken.decode auth_token
rescue JWT::ExpiredSignature
return
end
#current_user ||= User.find_by(auth_token: auth_token)
end
end
def log_out(user)
logged_in? ? user.generate_authentication_token! : user.destroy_token!
auth_token = user.auth_token
user.update_attribute(:auth_token, auth_token)
end
def logged_in?
current_user.present?
end
def authenticate_with_token!
render json: { errors: "Not authenticated" }, status: :unauthorized unless logged_in?
end
def log_in(user)
create_session(user)
user.generate_authentication_token!
user.update_attribute(:auth_token, user.auth_token)
end
def authenticate_as_self_or_admin!
render json: { errors: "Not authorized" }, status: :unauthorized unless is_self? || is_admin?
end
def is_self?
user = User.find(params[:id])
auth_token = request.headers["Authorization"]
auth_token = auth_token.split(" ").last if auth_token
user.auth_token != auth_token
end
def is_admin?
if logged_in? && current_user.authenticate(params[:password])
current_user.admin
end
end
end
sessions_controller.rb
class Api::SessionsController < ApplicationController
before_action :authenticate_with_token!, only: [:destroy]
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
render json: user, status: :created
else
render json: user, status: :unprocessable_entity
end
end
def destroy
log_out current_user
render status: 204
end
end
user.rb
require 'json_web_token'
class User < ApplicationRecord
attr_reader :current_password
before_save { email.downcase! }
before_create :generate_authentication_token!
before_update :reset_confirmed!, :if => :email_changed?
has_secure_password
has_many :posts
has_many :comments
has_many :votes
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :username, presence: true, length: { maximum: 24 }, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 8 }
validates :auth_token, uniqueness: true
def generate_authentication_token!
begin
self.auth_token = JsonWebToken.encode('id' => self.id, 'username' => self.username, 'email' => self.email, 'bio' => self.bio, 'confirmed' => self.confirmed, 'admin' => self.admin, 'points' => self.points)
end while self.class.exists?(auth_token: auth_token)
end
def destroy_token!
self.auth_token = nil
end
def reset_confirmed!
self.confirmed = false
end
def upvotes
self.votes.where(polarity: 1)
end
def downvotes
self.votes.where(polarity: -1)
end
def update_with_password(user_params)
current_password = user_params.delete(:current_password)
user_params[:password] = current_password if user_params[:password].nil?
if self.authenticate(current_password)
self.update(user_params)
else
self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
false
end
end
end
No, I am not using devise.
I'm really hoping my eyes are just tired here...
It turns out that current_user was in fact being called since it is the default scope_name for Active Model Serializers. I changed the name of my current_user method to avoid this conflict. Here are the relevant docs.

Not able to find admin? while doing Michael Hartl's Tutorial

This is my users controller and i am doing michael hartl's tutorial but i am having problem in current_user.admin? in the admin_user method defined in users controller and also having problem in my destroy method as i am not able to delete user as well.
pls any solution??
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = 'Welcome to the Sample App!'
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = 'Profile Updated'
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = 'User deleted'
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
def logged_in_user
unless logged_in?
store_location
flash[:danger] = 'Please log in.'
redirect_to login_url
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
User.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
has_secure_password
validates :password, length: { minimum: 6 }
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_digest, nil)
end
end
Link for the Delete
<li>
<%= gravatar_for user %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to 'delete', user, method: :delete,
data: { confirm: 'You sure?' } %>
<% end %>
</li>

Michael Hartl's Rails Tutorial: undefined method `authenticate_with_salt' error

I'm at the end of 9th chapter and i'm getting an error on the root page itself..
sessions helper is
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
current_user = user
end
def current_user
#current_user ||= user_from_remember_token
end
def signed_in?
!current_user.nil?
end
def sign_out
cookies.delete(:remember_token)
current_user = nil
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil, nil]
end
end
here is my user.rb
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:confirmation => true,
:length => {:within => 6..40 }
before_save :encrypt_password
def signed_in?
!current_user.nil?
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt)? user : nil
end
private
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
end
and my session_controller is
class SessionsController < ApplicationController
def new
#title = "Sign in"
end
def create
user = User.authenticate(params[:session][:email], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
redirect_to user
end
end
def destroy
sign_out
redirect_to root_path
end
end
and users_controler is
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
#title = #user.name
end
def new
#user = User.new
#title = "Sign up"
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
#title = "Sign up"
render 'new'
end
end
end
thing is i'm a beginer in Rails and i was going through this tutorials n got stuck right here.
Pls help guyz
here is the screenshot of the error
error says: undefined method 'authentication_with_salt'
I think it is similar issue that was asked and the link is here
You miss current_user scope. Check the above link and hope you can fix your issue asap.

uninitialized constant User::CompaniesRate

I am newbie in rails. I am trying to generate a page form. but I am geting this error.
I could not understand where is my problem.
this was the error showing and it was highlighting in this line
#companies_rates =#user.companies_rates
Here I will be having userpage, companies_rate and page3 where each pages have user id and companies rate has an column same column also exit in the page 3. Now i want display companies_rate and page 3 seperately
NameError in UsersController#show
uninitialized constant User::CompaniesRate
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
**#companies_rates =#user.companies_rates**
#title=#user.name
end
Here is my users controller
class UsersController < ApplicationController
before_action :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
#companies_rates =#user.companies_rates
#title=#user.name
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to skillable"
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Before filters
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
And here is my companies_rate controller
class CompaniesRatesController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
#companies_rates = companies_rates.all
end
def show
#companies_rates = companies_rate.find(params[:id])
end
def new
#companies_rates = companies_rates.new
end
def create
#companies_rates = companies_rates .new(params[:company,:r1,:r2,:r3])
if #post.save
redirect_to companies_rates _path, :notice => "Your post was saved"
else
render "new"
end
end
def edit
end
def update
end
def destroy
end
private
def companies_rates_params
params.require(:companies_rates).permit(:company, :r1, :r2, :r3 )
end
def correct_user
#companies_rates = current_user.companies_rates.find_by(id: params[:id])
redirect_to root_url if #ompanies_rates.nil?
end
end
Here is my users modal
class User < ActiveRecord::Base
attr_accessor :password
#attr_accessible :name, :email, :password, :password_confirmation
has_many :companies_mines
has_many :companies_rates
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
Here is my companies_rates
class CompaniesRates < ActiveRecord::Base
#attr_accessible :company, :r1, :r2, :r3
belongs_to :user
validates :company, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
belongs_to :user
default_scope :order => 'companies_rates.created_at DESC'
end
Can any on tell what is my problem and how to solve it.
Change the model name to CompaniesRate.Model name should be singular

Session usage in rails 3.1.3, returning errors

I am in a process of upgrading my app from rails 2.3.11 to 3.2.x. Everything worked well untill 3.1.x where I faced issues in session handling. Earlier I have utilized cookies for session handling but now there is a question if I can use ActiveModel for handling sessions too?????
Secondly, while still playing around with cookies, I see this unavoidable undefined method error. Any suggestions to get around this error????
Here is my codes-
Session Controller:
class SessionsController < ApplicationController
def new
#title = "Sign in"
end
def create
#title = "create session"
user = User.authenticate(params[:session][:name], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid username/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
#partner = Partner.find(:first, :conditions => [ "user_id = ?", user.id])
logger.info "---------User loggin: " + current_user.name
redirect_back_or samplings_url
end
end
def destroy
#title = "Sign out"
logger.info "---------User log OUT: " + current_user.name
sign_out
redirect_to root_path
end
end
User Model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password
EmailRegex = /\A[\w+\-._]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :name, :email
validates_length_of :name, :maximum => 50
validates_format_of :email, :with => EmailRegex
validates_uniqueness_of :email, :case_sensitive => false
has_many :microposts
validates_confirmation_of :password
validates_presence_of :password
validates_length_of :password, :within => 1..40
before_save :encrypt_password
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
def remember_me!
self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}")
save(validate=false)
end
private
def encrypt_password
unless password.nil? #due to def remember_me! method during sign in function call
self.salt = make_salt
self.encrypted_password = encrypt(password)
end
end
def encrypt(string)
secure_hash("#{salt}#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
UserController:
class UsersController < AuthController
before_filter :authenticate, :only => [:index, :edit, :update]
before_filter :correct_user, :only => [:new, :create, :destroy]
before_filter :modify_user, :only => [:edit, :update]
filter_parameter_logging :password
def index
#users = User.all
#title = "users"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
#title = #user.name
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def new
redirect_to signin_path
if !current_user?(#user)
flash[:notice] = "Only the partner who create the risorse can modify it."
end
end
def create
#title = "sign up user"
#user = User.new(params[:user]) #hash of user attributes
if #user.save
sign_in #user
flash[:success] = "Welcome to the microaqua web application!"
redirect_to #user #equal as user_path(#user)
else
#title = "Sign up"
render 'new'
end
end
# GET /users/1/edit
def edit
#title = #user.name #"user"
end
def update
#title = #user.name #"user"
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
def destroy
redirect_to users_path
end
private
def correct_user
#user = User.find(params[:id])
reroute() unless signed_in_and_master?
end
def modify_user
#user = User.find(params[:id])
reroute() unless (current_user?(#user) or signed_in_and_master?)
end
def reroute()
flash[:notice] = "Only the partner can modify his own profile."
redirect_to(user_path(#user))
end
end
Error:
NoMethodError in SessionsController#create
undefined method `encrypted_password' for #<ActiveRecord::Relation:0x00000003632038>
.where always returns an array. Here is the code that is throwing the error in your user model:
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
You are calling .encrypted_password on an array. Change the code to this:
def self.authenticate(name, submitted_password)
username = self.where(name: name).first
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
If it is possible to get more than one user with the same name then you should iterate through the array and check every result.
As far as storing the session in the database, check out this SO question:Rails 3: Storing Session in Active Record (not cookie)

Resources