Twitter API-Rails undefined method 'name' for nil: NilClass
I am working on a project that returns the date the user joined Twitter. When looking for a user that exists, everything works smoothly. However, when I search for a username that does not exist, I get this ugly error:
NoMethodError in WelcomeController#search_results
undefined method `name' for nil:NilClass
Here is my code:
def search_results
twitter_client = Twitter::REST::Client.new 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']
end
@name = params[:name]
@full_name = twitter_client.user_search(@name).first.name
created_at = twitter_client.user_search(@name).first.created_at
@created_at = created_at
@user_id = twitter_client.user_search(@name).first.id
end
I'm new to Rails and I believe I need to use Rescue or a flash error, but I'm not sure how to exactly implement it. Please advise.
Thank!
When the user does not exist with the username you are looking for, twitter_client.user_search(@name)
it finds nothing and the method first
returns nil
and you try to read the attribute name
from nil
.
This is why you are getting the error.
You can do it:
@name = params[:name]
user = twitter_client.user_search(@name).first
if user
@full_name = user.name
@created_at = user.created_at
@user_id = user.id
else
# do something else
end