I need help getting my ‘unless’ statement to work. It’s checking to see whether or not a db entry with the same date and user info already exists before it creates a new one.
Unfortunatley, it doesn’t seem to work. It allows duplicate entries to be made.
class Tweet < ActiveRecord::Base
def self.get_latest
Twitter::Search.new.hashtag("somesearch").fetch.each do |tweet_results| #hit the API.
twitter_created_at = DateTime.parse(tweet_results.created_at)
unless Tweet.exists?(['twitter_created_at = ? AND from_user_id_str = ?', DateTime.parse(tweet_results.created_at), tweet_results.from_user_id_str])
Tweet.create!({
:from_user => tweet_results.from_user,
:from_user_id_str => tweet_results.from_user_id_str,
:profile_image_url => tweet_results.profile_image_url,
:text => tweet_results.text,
:twitter_created_at => twitter_created_at
})
end
end
end
end
I think you need to provide an exit action; you haven’t created parameters for what occurs if a duplicate is found in your DB.
Perhaps if you use an if/else statement:
if Tweet.exists?(['twitter_created_at = ? AND from_user_id_str = ?', DateTime.parse(tweet_results.created_at), tweet_results.from_user_id_str])
prints "Generic Error Message" #This would be your response to a duplicate
else
Tweet.create!({
:from_user => tweet_results.from_user,
:from_user_id_str => tweet_results.from_user_id_str,
:profile_image_url => tweet_results.profile_image_url,
:text => tweet_results.text,
:twitter_created_at => twitter_created_at
})
end
end
end
end
Also, you seem to have 2 variables buried in a string with a #{} to separate them from the string. Is that intentional?
@wadjorlolo: the #{} syntax shouldn’t be used for passing variables into database queries, as Jon is doing here. The reason is that SQL code could be injected into the string, and your app will pass it straight on to the database, which could open you up to attacks.