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 = 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-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.
Thanks!
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 = user.name
@created_at = user.created_at
@user_id = user.id
else
# do something else
end