I'm trying to execute a before save definition like so in my Route.rb
file. (@current_user.email is causing the error)
class Route < ActiveRecord::Base
before_save { |route| route.created_by = @current_user.email }
end
But I get this error,
undefined method `email' for nil:NilClass
But I can use it just fine in my _header.html.erb
Like so:
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
<%= @current_user.email %>
<span class="caret"></span>
@current_user
is described in my sessions_helper
like so:
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def current_user?(user)
user == current_user
end
def sign_out
current_user = nil
cookies.delete(:remember_token)
end
end
Why am I not able to execute this before_save
without getting that error? Thanks guys.
Further to my comment, your SessionsHelper
looks similar to that of The Rails Tutorial . Given that, I think you have some issues with your current_user
and current_user=
methods as they seem to be doing the opposite thing. They should probably be:
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def current_user=(user)
@current_user = user
end
Edit
The model should not know about controller or helper methods , so you might want to set @route.created_by = current_user.email
somewhere in the relevant controller before you save the object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.