【发布时间】:2015-05-10 22:28:43
【问题描述】:
我正在使用Twitter Gem 从用户的时间线中提取和保存推文。在保存每个message 之前,我想通过将新消息的tweet_id 与已经保存在数据库中的tweet_id 的数组进行比较来检查这条记录是否已经存在。无论我尝试什么,我仍然看到重复的记录保存在messages 表中。这是我得到的:
控制器调用:
@messages = Message.pull_tweets(@user)
“pull_tweets”方法:
def self.pull_tweets(user)
tweets = $twitter.home_timeline # API call to pull all tweets from the timeline
if tweets && tweets.each { |tweet| validate_uniqueness_of(user,tweet) }
tweets.each { |tweet| user.messages.create!(tweet_id: tweet.id ... }
...
else
...
end
end
“validate_uniqueness_of”方法:
def self.validate_uniqueness_of(user,tweet)
if user.messages.pluck(:tweet_id).exclude?(tweet.id.to_s)
return true
else
return false
end
end
【问题讨论】:
-
您可以在消息模型中简单地使用
validates :tweet_id, uniqueness: true -
好像你永远不知道 ActiveRecord 的 exists? 方法。
标签: ruby-on-rails ruby activerecord twitter rails-activerecord