If else not working?


#1

I get the following error when I try to login into my admin back end:

NoMethodError in MemberController#index

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.login

RAILS_ROOT: C:/Ruby/MyProjects/ipod-give-away.com
Application Trace | Framework Trace | Full Trace

app/controllers/member_controller.rb:17:in `index’

Request

Parameters:

None

Show session dump

Response

Headers:

{“cookie”=>[],
“Content-Type”=>"",
“Cache-Control”=>“no-cache”}

My code:
def index
@oLogin = User.find_by_login(params[:l])
if @oLogin.login
@sLoggedInName = @oLogin.login + “, you’ve logged in successfully”
else
render :controller => ‘sessions’
end
end


#2

Cause it didn’t return any object.
so you must check the @oLogin first.

On Tue, Mar 10, 2009 at 11:11 AM, Chris G. <
removed_email_address@domain.invalid> wrote:

Response
if @oLogin.login
@sLoggedInName = @oLogin.login + “, you’ve logged in successfully”
else
render :controller => ‘sessions’
end
end

Posted via http://www.ruby-forum.com/.


[73, 32, 108, 111, 118, 101, 32, 121, 111, 117, 32, 115, 111, 32, 109,
117,
99, 104, 33].map{|c| c.chr}.join

Only two surfaces of a box:
http://blog.pixnet.net/zusocfc


#3

Chris G. wrote:

def index
@oLogin = User.find_by_login(params[:l])
if @oLogin.login
@sLoggedInName = @oLogin.login + “, you’ve logged in successfully”
else
render :controller => ‘sessions’
end
end

Aesthetically, I’d change @oLogin to @user, since User.find… will
return a User instance. I’d also avoid Hungarian notation and camelCase
variable names.

I think the actual problem is that your call to render is wrong. I’m
guessing you want a redirect. You might also want to read up on flash
for messaging to the user. I’d probably write this method something like
this:

def index
@user = User.find_by_login(params[:l])
if @user
flash[:notice] = “#{@user.login}, you’ve logged in successfully”
else
redirect_to :controller => ‘sessions’, :action => ‘new’
end
end