Twitter API- Rails undefined method `name' for nil:NilClass

I'm working on a project that returns the date of when a user joined Twitter. In searching for a user that exists, everything works smoothly. However, when I search for a username that doesn't exist, I'm given this ugly error:

  NoMethodError in WelcomeController#search_results
  undefined method `name' for nil:NilClass

Here is my code:

 def search_results
    twitter_client = do |config|
      config.consumer_key        = ENV['twitter_consumer_key']
      config.consumer_secret     = ENV['twitter_consumer_secret']
      config.access_token        = ENV['twitter_access_token']
      config.access_token_secret = ENV['twitter_access_token_secret']
    @name = params[:name]
    @full_name = twitter_client.user_search(@name)
    created_at = twitter_client.user_search(@name).first.created_at
    @created_at = created_at    
    @user_id = twitter_client.user_search(@name)

I'm new-ish to Rails and I believe I have to use Rescue or a flash error, but am not sure how to accurately implement it. Please advise.



When a user does not exist with the username you search for, twitter_client.user_search(@name) finds nothing, and first method returns nil, and you are trying to read the name attribute from nil.

That's why you get the error.

You can do this:

@name = params[:name]
user = twitter_client.user_search(@name).first
if user
     @full_name =
     @created_at = user.created_at    
     @user_id =
     # do something else

Need Your Help

VBA: How do I get this code to write 2-digit filenames only?

vba powerpoint powerpoint-vba

I am using the following VBA code to export PPT slides to images. The problem is that, for Slides 1 through 9, the filenames have only one character (eg: "1.png"). I need for those first nine slide...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.