Forum: Ruby on Rails If else not working?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7759594c66801d6f311ff38fd3ddef2a?d=identicon&s=25 Chris Gunnels (ballhogjoni)
on 2009-03-10 04:11
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
A1b97dafea62b11e7b3bef338ce3fe83?d=identicon&s=25 Billy Hsu (cfc)
on 2009-03-10 04:37
(Received via mailing list)
Cause it didn't return any object.
so you must check the @oLogin first.

On Tue, Mar 10, 2009 at 11:11 AM, Chris Gunnels <
rails-mailing-list@andreas-s.net> 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
5170ca260dbd2cdfd5a887a4dba7636f?d=identicon&s=25 Jeremy Weiskotten (jeremy_weiskotten)
on 2009-03-10 15:28
Chris Gunnels 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
This topic is locked and can not be replied to.